Java中泛型类型理解
1:不使用泛型类:
class Test1{}
Test1 in1=new Test1(new Integer(81));
Integer i1 = (Integer)in1.getObj(); //此处需要强制转换
System.out.println(in1.getObj().getClass().getName()+":"+i1);
2:使用泛型类:
Class Test <T>{}
Test<Integer> in=new Test(new Integer(8));
Integer i = in.getObj(); //此处不需要做强制转换
System.out.println(in.getObj().getClass().getName()+":"+i);
结论:如果不使用泛型,那么在后期取数据的时候需要强制转换类型。强制转换类型可能会因为类型转换错误,从而在运行时抛出错误
Java泛型的高级应用
1:限制泛型
class GenericsFoo,这样类中的泛型T只能是Collection接口的实现类,传入非Collection接口编译会出错
2:多接口限制
虽然Java泛型简单的用 extends 统一的表示了原有的 extends 和 implements 的概念,但仍要遵循应用的体系,Java 只能继承一个类,但可以实现多个接口,所以你的某个类型需要用 extends 限定,且有多种类型的时候,只能存在一个是父类,并且父类写在第一位,接口列在后面,也就是:
<T extends SomeClass & interface1 & interface2 & interface3>
3:通配符泛型
为了解决类型被限制死了不能动态根据实例来确定的缺点,引入了“通配符泛型”,使用通配泛型格式为
CollectionFool<?> fool=null; //使用通配符的方式
fool=new CollectionFool<ArrayList>(new ArrayList());
泛型方法
是否拥有泛型方法,与其所在的类是否泛型没有关系。要定义泛型方法,只需将泛型参数列表置于返回值前。如:
```
public class ExampleA {
public <T> void f(T x) {
System.out.println(x.getClass().getName());
}
public static void main(String[] args) {
ExampleA ea = new ExampleA();
ea.f(" ");
ea.f(10);
ea.f('a');
ea.f(ea);
}
}
“`
以上内容的参考资料:
参考资料:
http://baike.baidu.com/link?url=JgPvpMZUrPNh9ymtoV6tL4ZcWSRcIKFtYQMc6_c3ms6QU-vlofuaN58OpZCvIuG2uO5FpkgIbvqM1VyfMhhMvK