本文介绍了如何使用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列表转换为更通用的列表,而无需浏览列表中的每个项目

The return statement does a casting that doesn't compile. How can I convert the myPojos list to the more generic list, without having to go through each item of the list?

感谢

推荐答案

更改您的方法以使用通配符:

Change your method to use a wildcard:

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

    return myPojos;
}

这将阻止来电者尝试添加 >接口的实现到列表。或者,你可以写:

This will prevent the caller from trying to add other implementations of the interface to the list. Alternatively, you could just write:

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

如注释中所述:


  • 返回通配符的集合对于调用者来说可能很麻烦

  • 通常最好使用接口而不是具体类型作为返回类型。因此,建议的签名可能是以下之一:

  • Returning wildcarded collections can be awkward for callers
  • It's usually better to use interfaces instead of concrete types for return types. So the suggested signature would probably be one of:

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


这篇关于如何使用Java中的泛型来投射列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 19:16