How can I cast a list using generics in Java?

前端 未结 5 1543
刺人心
刺人心 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 09:57

    Try to use interfaces everywhere except when constructing instances, and you problems will go away:

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

    As others have said already, the use of MyInterface fixes your problem. It is also better to use the List interface instead of ArrayList for return types and variables.

    0 讨论(0)
  • 2021-02-02 10:02

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

    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<MyInterface> getMyInterfaces()
      public Collection<MyInterface> getMyInterfaces()
      public Iterable<MyInterface> getMyInterfaces()
      
    0 讨论(0)
  • 2021-02-02 10:10

    In this case, I would do it like this:

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

    MyPojo ist of type MyInterface (as it implements the interface). This means, you can just create the List with the Interface you need.

    0 讨论(0)
  • 2021-02-02 10:14

    Choosing the right type from the start is best, however to answer your question you can use type erasure.

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

    0 讨论(0)
  • 2021-02-02 10:18

    You should be doing:

    public ArrayList<MyInterface> getMyInterfaces() {   
       ArrayList<MyInterface> myPojos = new ArrayList<MyInterface>(0);    
       myPojos.add(new MyPojo(0));    
       myPojos.add(new MyPojo(1));    
       return myPojos;
    }
    
    0 讨论(0)
提交回复
热议问题