//首先我对泛型的理解就是可以把任何Object的子类当做类中的类型,下面是对于泛型的基本定义
public class GenericT<Object> {//泛型可接受类型是 Object 的 子类
private Object foo;
public void setFoo(Object foo){
this.foo=foo;
}
public Object getfoo(){
return foo;
}
}
然后对于泛型 ,可以有两个类型或者更多:
public class GenericTT<T1,T2> {
private T1 foo1;
private T2 foo2;
public T1 getFoo1() {
return foo1;
}
public void setFoo1(T1 foo1) {
this.foo1 = foo1;
}
public T2 getFoo2() {
return foo2;
}
public void setFoo2(T2 foo2) {
this.foo2 = foo2;
}
}
public class GenericTArray<T1>{//这里貌似不能直接用T
private T1[] fooArrayTs;
public T1[] getFooArrayTs() {
return fooArrayTs;
}
public void setFooArrayTs(T1[] fooArrayTs) {
this.fooArrayTs = fooArrayTs;
}
}
泛型可以像类一样继承另一个泛型:
public class GenericA<T1,T2>{
private T1 foo1;
private T2 foo2;
public T1 getFoo1() {
return foo1;
}
public void setFoo1(T1 foo1) {
this.foo1 = foo1;
}
public T2 getFoo2() {
return foo2;
}
public void setFoo2(T2 foo2) {
this.foo2 = foo2;
}
}
public class GenericB<T1,T2,T3> extends GenericA<T1, T2>{
private T3 foo3;
public T3 getFoo3() {
return foo3;
}
public void setFoo3(T3 foo3) {
this.foo3 = foo3;
}
}
下面是对于泛型的实例化:
public class GenericFooDemo {
public static void main(String[] argc){
GenericT<Boolean> foo1 = new GenericT<Boolean>();
GenericT<Integer> foo2 = new GenericT<Integer>();
foo1.setFoo(new Boolean(true));
Boolean b= foo1.getfoo();
System.out.println(b);
foo2.setFoo(new Integer(10));
Integer i= foo2.getfoo();
System.out.println(i);
GenericTT<String, Boolean> dui=new GenericTT<>();
dui.setFoo1("test");
dui.setFoo2(true);
System.out.println(dui.getFoo1()+" "+dui.getFoo2());
String[] strs={"hee","sadf","sdf"};
GenericTArray<String> fooStrs=new GenericTArray<String>();
fooStrs.setFooArrayTs(strs);
for(String s:fooStrs.getFooArrayTs()){
System.out.println(s);
}
GenericB<Integer, Boolean, String> extendsB =new GenericB<Integer, Boolean, String>();
extendsB.setFoo1(12);
extendsB.setFoo3("test");
System.out.println(extendsB.getFoo1()+" "+extendsB.getFoo3());
}
}