Can't add value to the Java collection with wildcard generic type

后端 未结 4 1705
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 12:06

Why this code does not compile (Parent is an interface)?

List list = ...
Parent p = factory.get();   // returns concrete         


        
4条回答
  •  一生所求
    2020-11-22 12:51

    It's doing that for the sake of safety. Imagine if it worked:

    List childList = new ArrayList();
    childList.add(new Child());
    
    List parentList = childList;
    parentList.set(0, new Parent());
    
    Child child = childList.get(0); // No! It's not a child! Type safety is broken...
    

    The meaning of List is "The is a list of some type which extends Parent. We don't know which type - it could be a List, a List, or a List." That makes it safe to fetch any items out of the List API and convert from T to Parent, but it's not safe to call in to the List API converting from Parent to T... because that conversion may be invalid.

提交回复
热议问题