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

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

}
share improve 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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值