How can I cast a list using generics in Java?

前端 未结 5 1547
刺人心
刺人心 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 getMyInterfaces()
    {
        List myInterfaces = new ArrayList(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.

提交回复
热议问题