java中的泛型(E)
泛型:就是一种不确定的数据类型。
比如:ArrayList E就是泛型。 这种不确定的数据类型需要在使用这个类的时候才能够确定出来。
泛型可以省略,如果省略,默认泛型是Object类型。
泛型的好处:1. 省略了强转的代码。2. 可以把运行时的问题提前到编译时期。
如:
myGenericity.java
public class myGenericity<E> {
private E i;
public void set(E j) {
this.i = j;
}
public E get() {
return (E) i;
}
}
test0.java
public class test0 {
public static void main(String[]args) {
myGenericity<String> my = new myGenericity();
my.set("String类型");
System.out.println(my.get());
myGenericity<Integer> my2 = new myGenericity();
my2.set(12);
System.out.println(my2.get());
}
}
执行结果
String类型
12