
本站地址:http://www.bajiao123.com

JDK5.0的11个主要新特征-Java技术
Integer i = 100;受限泛型是指类型参数的取值范围是受到限制的. extends关键字不仅仅可以用来声明类的继承关系, 也可以用来声明类型参数(type parameter)的受限关系.例如, 我们只需要一个存放数字的列表, 包括整数(Long, Integer, Short), 实数(Double, Float), 不能用来存放其他类型, 例如字符串(String), 也就是说, 要把类型参数T的取值泛型限制在Number极其子类中.在这种情况下, 我们就可以使用extends关键字把类型参数(type parameter)限制为数字
示例
public class Limited<T extends Number> {
public static void main(String[] args) {
Limited<Integer> number; //正确
Limited<String> str; //编译错误
}
}
1.4 泛型与异常
类型参数在catch块中不允许出现,但是能用在方法的throws之后。例:
import java.io.*;
interface Executor<E extends Exception> {
void execute() throws E;
}
public class GenericExceptionTest {
public static void main(String args[]) {
try {
Executor<IOException> e = new Executor<IOException>() {
public void execute() throws IOException{
// code here that may throw an
// IOException or a subtype of
// IOException
}
};
e.execute();
} catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}
}
1.5 泛型的通配符"?"
"?"可以用来代替任何类型, 例如使用通配符来实现print方法。
public static void print(GenList<?> list) {})
1.6 泛型的一些局限型
不能实例化泛型
T t = new T(); //error
不能实例化泛型类型的数组
T[] ts= new T[10]; //编译错误
不能实例化泛型参数数
Pair<String>[] table = new Pair<String>(10); // ERROR
类的静态变量不能声明为类型参数类型
public class GenClass<T> {
private static T t; //编译错误
}
泛型类不能继承自Throwable以及其子类
public GenExpection<T> extends Exception{} //编译错误
不能用于基础类型int等
Pair<double> //error
Pair<Double> //right
旧的循环
Linke
上一页 [1] [2] [3] [4] [5] [6] [7] [8] 下一页
本站地址:http://www.bajiao123.com

