Please consider the following snippet:
public interface MyInterface {
public int getId();
}
public class MyPojo implements MyInterface {
private int i
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.
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:
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()
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.
Choosing the right type from the start is best, however to answer your question you can use type erasure.
return (ArrayList<MyInterface>) (ArrayList) myPojos;
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;
}