1.泛型类型必须是引用类型,不能是像int、double或char这样的基本类型来代替泛型类型。例如以下的语句是错误的:
ArrayList<int> intList = new ArrayList<int>();
2.自动解包:如果元素是包装类型,例如:Integer、Double或Character,那么可以直接将这个元素赋给一个基本类型的变量。如入如下代码:
ArrayList <Double> list = new ArrayList<Double>();
list.add(5.5);
list.add(3.0);
Double doubleObject =list.get(0);
double d=list.get(1);
在第二行和第三行,5.5和3.0自动转型为Double对象,并添加到list中,在第四行中,list中的第一个元素被赋给一个Double变量。但是在第五航中,list中的第二个元被赋给一个double变量。list.get(1)中的对象自动转换为一个基本类型的值。
3.通配泛型
public class WildCardDemo1 {
public static void main(String[] args ) {
GenericStack<Integer> intStack = new GenericStack<Integer>();
intStack.push(1); // 1 is autoboxed into new Integer(1)
intStack.push(2);
intStack.push(-2);
System.out.print("The max number is " + max(intStack));
}
// Find the maximum in a stack of numbers
public static double max(GenericStack< Number> stack) {
double max = stack.pop().doubleValue(); // initialize max
while (!stack.isEmpty()) {
double value = stack.pop().doubleValue();
if (value > max)
max = value;
}
return max;
}
}
以上代码会在第8行编译出错,因为intStack不是GenericStack<Number>的实例,他只是GenericStack<Integer>的实例。虽然Integer是Number的子类,但是GenericStack<Integer>并不是GenericStack<Integer>的子类型。为了避免这个问题,应使用通配泛型类型。通配泛型类型有三中形式-------?、? extends T或者? supper T,其中T是某个泛型类型。故上面第12行代码应该改为
public static double max(GenericStack<? extends Number> stack) {
4不管实际的具体类型是什么,泛型类是被他的所有实例所共享。例如按照如下创建list1和list2
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<String> list2 = new ArrayList<String>();
尽管在编译时,ArrayList<string>和ArrayList<Integer>是两种类型,但是在运行时,只有一个ArrayList类被加载到JVM。list1是ArrayList的实例,而不是ArrayList<string>的实例。由于ArrayList<string>并没有在JVM中存储为单独的一个类。
5.使用泛型的限制:
5.1不能使用new E()和new E[],例如以下的语句是错误的。
E oj=new E();
E [] elements=new E[capacity];
但是可以创建一个Object类型,然后使用强制类型转换为E[]来规避这个错误:
E [] elements=(E[])new Object[capacity];
ArrayList<String> [] List = new ArrayList<String>[];//这是错的
ArrayList<String> [] List = (ArrayList<String>)new ArrayList<String>[10];//这是对的,但是会有编译警告
5.2在静态环境下不允许类的参数是泛型类型
5.3异常类不能是泛型,因为泛型类不能扩展java.lang.Throwable。
总结:使用泛型的主要优势实在编译时发现错误,而非运行时发现错误,和扩展型性。