Java using generics with lists and interfaces

后端 未结 6 1743
遇见更好的自我
遇见更好的自我 2021-01-13 11:02

Ok, so here is my problem:

I have a list containing interfaces - List a - and a list of interfaces that extend that interface: Li

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 11:50

    Just to explain why Java does not permit this:

    • A List is a list in which you can put any object implementing Record, and every object you get out will implement Record.
    • A List is a list in which you can put any object implementing SubRecord, and every object you get out will implement SubRecord.

    If it would be allowed to simply use a List as a List, then the following would be allowed:

    List subrecords = new ArrayList();
    List records = subrecords;
    records.add(new Record()); // no problem here
    
    SubRecord sr = subrecords.get(0); // bang!
    

    You see, this would not be typesafe. A List (or any opject of a parametrized class, in fact) can not typesafely change its parameter type.

    In your case, I see these solutions:

    • Use List from start. (You can add SubRecord objects to this without problems.)
      • as a variation of this, you can use List for the method which adds stuff. List is a subtype of this.
    • copy the list:

      List records = new ArrayList(subrecords);
      

    To exand a bit on th variation:

    void addSubrecords(List subrecords) {
        ...
    }
    
    
    List records = new ArrayList();
    addSubrecords(records);
    recordkeeper.records = records;
    

提交回复
热议问题