繁体   English   中英

如何在Java中使用泛型来转换列表?

[英]How can I cast a list using generics in Java?

请考虑以下代码段:

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列表转换为更通用的列表, 而不必遍历列表中的每个项目

谢谢

更改方法以使用通配符:

public ArrayList<? extends MyInterface> getMyInterfaces() {    
    ArrayList<MyPojo> myPojos = new ArrayList<MyPojo>(0);
    myPojos.add(new MyPojo(0));
    myPojos.add(new MyPojo(1));

    return myPojos;
}

这将阻止调用者尝试将该接口的其他实现添加到列表中。 或者,你可以写:

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;
}

正如评论中所讨论的:

  • 返回通配符集合对于调用者来说可能很尴尬
  • 通常最好使用接口而不是返回类型的具体类型。 所以建议的签名可能是以下之一:

     public List<MyInterface> getMyInterfaces() public Collection<MyInterface> getMyInterfaces() public Iterable<MyInterface> getMyInterfaces() 

从一开始就选择正确的类型是最好的,但是要回答你的问题,你可以使用类型擦除。

return (ArrayList<MyInterface>) (ArrayList) myPojos;

你应该这样做:

public ArrayList<MyInterface> getMyInterfaces() {   
   ArrayList<MyInterface> myPojos = new ArrayList<MyInterface>(0);    
   myPojos.add(new MyPojo(0));    
   myPojos.add(new MyPojo(1));    
   return myPojos;
}

在这种情况下,我会这样做:

public ArrayList<MyInterface> getMyInterfaces() {

    ArrayList<MyInterface> myPojos = new ArrayList<MyInterface>(0);
    myPojos.add(new MyPojo(0));
    myPojos.add(new MyPojo(1));

    return myPojos;
}

MyPojo是MyInterface类型的(因为它实现了接口)。 这意味着,您只需使用所需的接口创建List。

除了在构造实例时,尝试在任何地方使用接口,并且问题将消失:

public List<MyInterface> getMyInterfaces()
{
    List<MyInterface> myInterfaces = new ArrayList<MyInterface>(0);
    myInterfaces.add(new MyPojo(0));
    myInterfaces.add(new MyPojo(1));

    return myInterfaces;
}

正如其他人已经说过的那样,使用MyInterface可以解决您的问题。 对于返回类型和变量,最好使用List接口而不是ArrayList。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM