泛型作用总结
1、提高Java程序的类型安全
集合中可以添加Object类型的对象,如果在不使用泛型的情况下定义了一个ArrayList对象,那么各种类的对象都可以添加到该集合中。而在从集合中取值时,都需要进行强制类型转换,可以把取出的对象转换成任意类型,但是编译时不报错,但是运行时会发生ClassCastException异常。
2、消除强制类型转换。
泛型可以消除源代码中的许多强制类型转换,这样可以使代码可读性更好,并减少出错的机会.
泛型做为方法参数和方法重载
从下面的案例中可以看到,参数类型可以是Number的子类,所以方法调用时,参数是整型的123和浮点型的5.0f都是正确的,都可以输出结果。
1 public classGenericMethod {2
3 public static voidprintValue(T t) {4 System.out.println(t);5 }6
7 public static voidmain(String[] args) {8 printValue(123);9 printValue(5.0f);10 }11 }
结果如下:
如下图所示,在GenericMethod类中添加一个printValue()方法,参数类型是Integer,也就是Number的一个子类,会发现程序并没有报错,而是和上面的printValue(T t)方法形成了方法的重载。新增加方法的输出语句,增加了Integer:的输出,为了和上面的方法输出进行区分。
public classGenericMethod {public static voidprintValue(T t) {
System.out.println(t);
}public static voidprintValue(Integer n) {
System.out.println("Integer" +n);
}public static voidmain(String[] args) {
printValue(123);
printValue(5.0f);
}
}
运行结果如下:从运行结果可以看出,这里会优先调用Integer作为参数的printValue()方法,而不是泛型作为参数的方法。
下面再来看一种形式,增加了Number作为参数的方法,可以发现程序报错了。错误提示是:Erasure of method printValue(Number) is the same as another method in type GenericMethod,也就是这个方法和GenericMethod中的另一个方法一样,也就是和第一个T作为参数的方法一样。说明它们虽然表面看来不一样,但编译后的形式是一样的,因此这样写是不合法的。