如何在Java中使用generics来转换列表?
请考虑以下代码段:
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 getMyInterfaces() { ArrayList myPojos = new ArrayList(0); myPojos.add(new MyPojo(0)); myPojos.add(new MyPojo(1)); return (ArrayList) myPojos; }
return语句执行不编译的转换。 如何将myPojos列表转换为更通用的列表, 而无需遍历列表中的每个项目 ?
谢谢
更改方法以使用通配符:
public ArrayList extends MyInterface> getMyInterfaces() { ArrayList myPojos = new ArrayList (0); myPojos.add(new MyPojo(0)); myPojos.add(new MyPojo(1)); return myPojos; }
这将阻止调用者尝试将该接口的其他实现添加到列表中。 或者,你可以写:
public ArrayList getMyInterfaces() { // Note the change here ArrayList myPojos = new ArrayList (0); myPojos.add(new MyPojo(0)); myPojos.add(new MyPojo(1)); return myPojos; }
正如评论中所讨论的:
- 对于呼叫者而言,返回通配符集合可能很尴尬
-
通常最好使用接口而不是返回类型的具体类型。 所以建议的签名可能是以下之一:
public List
getMyInterfaces() public Collection getMyInterfaces() public Iterable getMyInterfaces()
从一开始就选择正确的类型是最好的,但是要回答你的问题,你可以使用类型擦除。
return (ArrayList
你应该这样做:
public ArrayList getMyInterfaces() { ArrayList myPojos = new ArrayList (0); myPojos.add(new MyPojo(0)); myPojos.add(new MyPojo(1)); return myPojos; }
在这种情况下,我会这样做:
public ArrayList getMyInterfaces() { ArrayList myPojos = new ArrayList (0); myPojos.add(new MyPojo(0)); myPojos.add(new MyPojo(1)); return myPojos; }
MyPojo是MyInterface类型(因为它实现了接口)。 这意味着,您只需使用所需的接口创建List。
除了在构造实例时,尝试在任何地方使用接口,并且问题将消失:
public List getMyInterfaces() { List myInterfaces = new ArrayList (0); myInterfaces.add(new MyPojo(0)); myInterfaces.add(new MyPojo(1)); return myInterfaces; }
正如其他人已经说过的那样,使用MyInterface可以解决您的问题。 对于返回类型和变量,最好使用List接口而不是ArrayList。