Why are arrays covariant but generics are invariant?

前端 未结 9 1464
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 00:44

From Effective Java by Joshua Bloch,

  1. Arrays differ from generic type in two important ways. First arrays are covariant. Generics are invariant.
  2. Cov

9条回答
  •  余生分开走
    2020-11-22 01:04

    We can’t write List l = new ArrayList(); because Java is trying to protect us from a runtime exception. You might think this would mean that we can’t write Object[] o = new String[0];. That isn’t the case. This code does compile:

    Integer[] numbers = { new Integer(42)};
    Object[] objects = numbers;
    objects[0] = "forty two"; // throws ArrayStoreException
    

    Although the code does compile, it throws an exception at runtime. With arrays, Java knows the type that is allowed in the array. Just because we’ve assigned an Integer[] to an Object[] doesn’t change the fact that Java knows it is really an Integer[].

    Due to type erasure, we have no such protection for an ArrayList. At runtime, the ArrayList doesn’t know what is allowed in it. Therefore, Java uses the compiler to prevent this situation from coming up in the first place. OK, so why doesn’t Java add this knowledge to ArrayList? The reason is backward compatibility; that is, Java is big on not breaking existing code.

    OCP reference.

    提交回复
    热议问题