I'm trying to write a method that will return a collection (eg Arraylist) that is declared using generics as containing either a parent class or a class that extends the parent class. For this method the objects in the collection will always be used as instances of the parent class but in other contexts they are used differently hence them being held separately. For example:
import java.util.ArrayList;
import java.util.Collection;
public class TestClass {
public static int PARENTTYPE=0;
public static int CHILDTYPE=1;
Collection<ParentClass> parentHolder=new ArrayList<ParentClass>();
Collection<ChildClass> childHolder=new ArrayList<ChildClass>();
public TestClass(){
}
public Collection<ParentClass> getHolder(int type){
if (type==PARENTTYPE){
return parentHolder;
}else if (type==CHILDTYPE){
return childHolder; //<--incompatible types
}else{
throw new RuntimeException("Not a valid type");
}
}
public static void main(String args[]){
TestClass test=new TestClass();
Collection<ParentClass> col1=test.getHolder(PARENTTYPE);
Collection<ParentClass> col2=test.getHolder(CHILDTYPE);
}
}
public class ParentClass {
}
public class ChildClass extends ParentClass{
}
However I receive an incompatible types exception at the indicated line. How can I write the method such that I can return collections declared as containing any objects that extend a certain class.
null
to such a collection, and you can remove elements from it, so it is not completely read only. – Lightship