I’m trying to create a container that would accept specific classes only. Using generics as follows:
static class Test1<C extends Test1> {
C field = null;
public C getField() {
return field;
}
public void setField(C field) {
this.field = field;
}
}
static class Test2 extends Test1{
}
class MainTest {
public static void main(String[] args) throws Exception {
List<Test1<? extends Test1>> list = new ArrayList<Test1<? extends Test1>>();
Test1<Test2> newInstance = new Test1<Test2>();
list.add(newInstance);
Test1<Test2> value = list.get(1);
}
}
Just want to understand why this List> would accept a newInstance object, but compilation time error occurs while I’m fetching “Test1 value” back?
Is there any chance to workaround the problem?
Thanks in advance.
UPDATE
Many noticed that ” Test1<? extends Test1>, where ? MAY NOT be equal to Test2.”
I totally agree but as far as I understand in this case I need to type cast the extracted value to Test1<Test2> and that means that the whole point of generics is lost in this case… Please correct me if I’m wrong.
Because when you
list.get(1)returnsTest1<? extends Test1>, where?MAY NOT be equal toTest2.On the onther hand
list.add(...)acceptsTest1<? extends Test1>, i.e. Test1 with ANY generics parameter which is inheritor of Test1.