java 泛型中T和?的区别

1.T代表的是未知的类型使用在方法中的参数或类的泛型中

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);
  }
}


2.?则表示泛型类中的泛指  是一个占位符  不能往容器中添加数据

// 注意ArrayList中不能加<?>
List<?> list = new ArrayList();
list.add(123);// 错误





猜你喜欢

转载自forlan.iteye.com/blog/2304816