Ok, so here is my problem:
I have a list containing interfaces - List
- and a list of interfaces that extend that interface: Li
Just to explain why Java does not permit this:
List
is a list in which you can put any object implementing Record
, and every object you get out will implement Record
.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:
List
from start. (You can add SubRecord
objects to this without problems.)
List super Subrecord>
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 super Subrecord> subrecords) {
...
}
List records = new ArrayList();
addSubrecords(records);
recordkeeper.records = records;