Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch Error : Cannont convert from ArrayList<SubClass1> to List<SuperClass>

Here is my class Structure, and where I am getting error

class SuperClass{
//variables
}

class SubClass1 extends SuperClass{
//variables
}

class SubClass2 extends SuperClass{
//variables
}

class AClass{
List<SuperClass> list;

public AClass(boolean b){
if(b)
list = new ArrayList<SubClass1>();//getting error here
else
list = new ArrayList<SubClass2>();//and here
}
void addObjects(SuperClass obj){
list.add(obj);
}

}

How can I solve this? Should I change my design ? How?

ADDITION:

When I changed

`List<SuperClass> list;`

to List<? extends SuperClass> list;

I am not getting the previous error but I am getting another error while adding objects,

The method add(capture#2-of ? extends SuperClass) in the type List<capture#2-of ? extends SuperClass> is not applicable for the arguments (SuperClass)

like image 425
Eternal Noob Avatar asked Apr 04 '11 00:04

Eternal Noob


1 Answers

It seems you're trying to create a list that only contains objects from the particular subclass. In this case you just need the generics to play nice at compile time. (Generics are erased at runtime :) )

class AClass<T extends SuperClass> {
    List<T> list;

    public AClass(){
        list = new ArrayList<T>();
    }

    void addObjects(T obj){
        list.add(obj);
    }

}
like image 120
Charlie Avatar answered Sep 21 '22 02:09

Charlie