如何在SparseArray容器中使用扩展类?

时间:2013-11-11 16:54:19

标签: java polymorphism containers

不应该这样吗?如果没有,那么有没有办法同样地做到这一点?

public abstract class BaseItem {
}

public class SpecificItem extends BaseItem {
    public int value;
}


public class AnAdapter{
    public AnAdapter(SparseArray<BaseItem> items){
    }
}

public class DifferenClass{
    public DifferenClass(){
        SparseArray<SpecificItem> items = new SparseArray<SpecificItem>();
        AnAdapter anAdapter = new AnAdapter(items); // here is wrong type   
    }
}

--------编辑: 更新。是否只有将特定元素附加到更通用容器的方法?所有这些铸件看起来都很脏。但是有效......

public abstract class BaseItem {
}

public class SpecificItem extends BaseItem {
    public int value;
}


public class AnAdapter{
    public AnAdapter(SparseArray<? extends BaseItem> items){
    }
}

public class DifferenClass{
    DifferenClass(){
        SparseArray<? extends BaseItem> items = new SparseArray<BaseItem>();
        ((SparseArray<SpecificItem>)items).append(0,new SpecificItem());
    }
}

2 个答案:

答案 0 :(得分:3)

使用wildcards

public class AnAdapter{
    public AnAdapter(SparseArray<? extends BaseItem> items){
    }
}

答案 1 :(得分:1)

在构造函数中,您只需:

 public class DifferenClass{
    DifferenClass(){
        SparseArray<BaseItem> items = new SparseArray<BaseItem>();
        items.append(0, new SpecificItem());
    }
}

补充阅读:covariance and contravariance