定义方法泛型
static <T> void addAll(List<T> list, T... data) {
list.addAll(Arrays.asList(data));
}
使用方法泛型
List<String> stringList = new ArrayList<>();
addAll(stringList, "hh", "aa", "mm", "dd", "jj");
System.out.println(stringList);
List<Integer> integerList = new ArrayList<>();
addAll(integerList, 1, 2, 4, 6, 7);
System.out.println(integerList);
定义类泛型
class GenericClass<T> {
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
使用类泛型
GenericClass<String> obj = new GenericClass<>();
obj.setData("hello");
String s = obj.getData();
GenericClass<Integer> obj2 = new GenericClass<>();
obj2.setData(123);
Integer i = obj2.getData();
GenericClass obj3 = new GenericClass();
Object oo = obj3.getData();