请考虑以下片段:
public interface MyInterface {
public int getId();
}
public class MyPojo implements MyInterface {
private int id;
public MyPojo(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
public ArrayList<MyInterface> getMyInterfaces() {
ArrayList<MyPojo> myPojos = new ArrayList<MyPojo>(0);
myPojos.add(new MyPojo(0));
myPojos.add(new MyPojo(1));
return (ArrayList<MyInterface>) myPojos;
}
return 语句执行了无法编译的转换。如何将 myPojos 列表转换为更通用的列表,无需遍历列表中的每一项?
Thanks
更改您的方法以使用通配符:
public ArrayList<? extends MyInterface> getMyInterfaces() {
ArrayList<MyPojo> myPojos = new ArrayList<MyPojo>(0);
myPojos.add(new MyPojo(0));
myPojos.add(new MyPojo(1));
return myPojos;
}
这将阻止调用者尝试添加other列表接口的实现。或者,你也可以这样写:
public ArrayList<MyInterface> getMyInterfaces() {
// Note the change here
ArrayList<MyInterface> myPojos = new ArrayList<MyInterface>(0);
myPojos.add(new MyPojo(0));
myPojos.add(new MyPojo(1));
return myPojos;
}
正如评论中所讨论的:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)