I feel stupid asking this but I am.
The line List<HasId> ids = list is giving a compile error in the following code:
public class MyGarbageClass {
public void myMethod(List<MyCompany> list){
List<HasId> ids = list;
}
interface HasId {
int getId();
}
class MyCompany implements HasId{
private int id = 5;
@Override
public int getId() {
return id;
}
}
}
MyCompany implements HasId so I thought I should be able to assign it. Why cant I? And more importantly, what is an easy way to assign this to HasId list of objects.
update: List ids = (List<HasId>)list; breaks also on inconvertible types
The reason why generic assignment like this is disallowed is it possible to do the cast and then add something to
idswhich is not a MyCompany (perhaps MyPerson which also implements HasId). So if the cast was allowed then you could do this.Now the list has broken the generic guarantee because you have list that was declared as
<MyCompany>with a MyPerson in it.You could cast it like this.
But add() operations will not be permitted, but you can iterate it to get the id if you wish.