Java参考分配与通用列表
我觉得很蠢,要求我这样。
I feel stupid asking this but I am.
List< HasId> ids = list
在下面的代码中给出一个编译错误:
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实现HasId我应该能够分配它。为什么不能我? 更重要的是,将一个简单的方法分配给HasId对象列表。
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.
更新:列表
不允许这样的泛型赋值的原因是可以做转换,然后添加一些到 ids
这不是一个MyCompany(也许MyPerson也实现HasId )。
The reason why generic assignment like this is disallowed is it possible to do the cast and then add something to ids
which is not a MyCompany (perhaps MyPerson which also implements HasId). So if the cast was allowed then you could do this.
public void myMethod(List<MyCompany> list){
List<HasId> ids = list;
ids.add(new MyPerson());
}
现在列表已经破坏了通用保证,因为您的列表已声明为 < MyCompany>
Now the list has broken the generic guarantee because you have list that was declared as <MyCompany>
with a MyPerson in it.
b
$ b
You could cast it like this.
public void myMethod(List<MyCompany> list){
List<? extends HasId> ids = list;
}
但不允许add()操作,如果你愿意,得到id。
But add() operations will not be permitted, but you can iterate it to get the id if you wish.