先简单来段例子:

public void testGenerics() {
       Collection numbers = new ArrayList<>();
       numbers.add(1); // ok

       Collection tmp = numbers;
       // don't work, you don't know what type 'tmp' obviously contains
//        tmp.add(1);

       Collection tmp2 = numbers;
       // don't work, you don't know what subtype 'tmp2' obviously contains
//        tmp2.add(1);

       Collection integers = new ArrayList<>();
       tmp = integers;
       tmp2 = integers;

       Collection strings = new ArrayList<>();
       tmp = strings;
//        tmp2 = strings; // don't work
   }

这个问题其实有点反人类,估计大部分人(包括我)对这种转换的第一反应肯定是“当然是对的。。”,说下我的理解:

说到为什么在不明确类型的情况下不能允许写操作,那是为了运行期的安全,举个例子:

public void testGenerics2() {
   List integers = new ArrayList<>();

   List comparables = integers;
   
   integers.add("1");
   
   comparables.get(0).intValue(); // fail
}

如果comparables允许添加Comparable类型,那么运行期就有可能会抛出一些意料之外的RuntimeException,导致方法不正常结束甚至程序crash。

现在再来说说Collection与Collection,又是很多人(包括我)第一反应肯定是“Object是所有java对象的公共父类,所以Collection可以表示任意类型的集合”,来看个例子:

public void testGenerics3() {
       List integers = new ArrayList<>();

       List objects = integers; // don't work
       List objects1 = integers; // ok
   }