语法:class/interface 类名/接口名{}
注意:T只是泛型的一个标准,使用什么字符都可以,但是都要大写(不要使用特殊字符,建议用T)
可以定义多个泛型,类名后面添加<T,E,F…>,就可以了
定义一个泛型
public class GenericTest<T> {
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
定义两个泛型
public class GenericTest2<T,E> {
private T t;
private E e;
public GenericTest2(T t, E e) {
this.t = t;
this.e = e;
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public E getE() {
return e;
}
public void setE(E e) {
this.e = e;
}
@Override
public String toString() {
return "GenericTest2{" +
"t=" + t +
", e=" + e +
'}';
}
}
测试类
public class Test {
public static void main(String[] args) {
//指定String类型
GenericTest<String> gt = new GenericTest<>();
gt.setT("泛型为String类型");
System.out.println(gt.getT());
//指定数组类型
GenericTest<Integer[]> gt2 = new GenericTest<>();
gt2.setT(new Integer[]{2,3,4});
GenericTest2<String, Date> gt3=new GenericTest2<>("浩哥",new Date());
GenericTest2<String, Integer> gt4=new GenericTest2<>("靓仔",18);
System.out.println(gt3+"\n"+gt4);
}
}
来源:CSDN
作者:林浩吧
链接:https://blog.csdn.net/weixin_45335305/article/details/104215004