How can I cast a list using generics in Java?

前端 未结 5 1542
刺人心
刺人心 2021-02-02 09:20

Please consider the following snippet:

public interface MyInterface {

    public int getId();
}

public class MyPojo implements MyInterface {

    private int i         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-02 10:02

    Change your method to use a wildcard:

    public ArrayList getMyInterfaces() {    
        ArrayList myPojos = new ArrayList(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 getMyInterfaces() {
        // Note the change here
        ArrayList myPojos = new ArrayList(0);
        myPojos.add(new MyPojo(0));
        myPojos.add(new MyPojo(1));
    
        return myPojos;
    }
    

    As discussed in the comments:

    • 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 getMyInterfaces()
      public Collection getMyInterfaces()
      public Iterable getMyInterfaces()
      

提交回复
热议问题