Why are arrays covariant but generics are invariant?

前端 未结 9 1285
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  梦毁少年i
    2020-11-22 01:21

    The reason is that every array knows its element type during runtime, while generic collection doesn't because of type erasure.

    For example:

    String[] strings = new String[2];
    Object[] objects = strings;  // valid, String[] is Object[]
    objects[0] = 12; // error, would cause java.lang.ArrayStoreException: java.lang.Integer during runtime
    

    If this was allowed with generic collections:

    List strings = new ArrayList();
    List objects = strings;  // let's say it is valid
    objects.add(12);  // invalid, Integer should not be put into List but there is no information during runtime to catch this
    
    
    

    But this would cause problems later when someone would try to access the list:

    String first = strings.get(0); // would cause ClassCastException, trying to assign 12 to String
    

    提交回复
    热议问题