开发者

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

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

class Su开发者_JAVA百科perClass{
//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)


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);
    }

}


You should use a bounded wildcard in your ArrayList declaration:

 class AClass{

      List<? extends SuperClass> list;

      public AClass(boolean b){
         if(b)
          list = new ArrayList<SubClass1>();
        else
          list = new ArrayList<SubClass2>();
        }
      }
}

The ? is a wildcard and defines an unknown type. But by using a bounded wildcard you can assure that it is an unknown subtype of SuperClass.

For further information about wildcards see here.

Concerning you're other problem:

The type of the parameter to list.add() is ? extends

SuperClass-- an unknown subtype of SuperClass. Since we don't know what type it is, we don't know if it is a supertype. it might or might not be such a supertype, so it isn't safe to pass a SubClass1 or SubClass2 there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜