泛型类
public class Test {
public static void main(String[] args) {
A<Integer> a = new A<>();
a.setKey(1);
System.out.println(a.getKey());
}
}
class A<T>{
private T key;
public void setKey(T key){
this.key = key;
}
public T getKey(){
return this.key;
}
}
泛型接口
public class Test1 {
public static void main(String[] args) {
B1<Integer> b1 = new B1<>();
B1<String> b11 = new B1<>();
B2 b2 = new B2();
}
}
interface IB<T>{
T test(T t);
}
class B1<T> implements IB<T>{
@Override
public T test(T t) {
return null;
}
}
class B2 implements IB<String>{
@Override
public String test(String s) {
return null;
}
}
泛型方法
- 泛型方法,在调用之前没有固定的数据类型,在调用时,传入的参数是什么类型,就会把泛型改成什么类型。
class cc{
public <T> void test(T s){
T t = s;
}
public <T> T test1(T s){
return s;
}
}
泛型通配符
- 不确定集合中的元素具体的数据类,使用?表示所有类型。
- 有限制的通配符:
public class Test2 {
public static void main(String[] args) {
Dd dd = new Dd();
List<String> stringList = new ArrayList<>();
dd.test(stringList);
List<Integer> integerArrayList = new ArrayList<>();
dd.test(integerArrayList);
}
}
class Dd{
public void test(List<?> list){
}
}