您的位置:首页 > 编程语言 > Java开发

Java中的范型类型强制转化注意2

2016-04-26 07:54 489 查看
Type mismatch Error : Cannont convert from ArrayList<SubClass1> to List<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);
}

}


shareimprove
this answer
你需要使用一个有界限的通配符在你的ArrayList声明中。

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


这个‘?’表示一个通配符,它定义个不知道的类型,但是使用一个有界限的通配符,你可以确定它是一个未确定的类型,这个类型是

SuperClass的子类型。

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: