不应该这样吗?如果没有,那么有没有办法同样地做到这一点?
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());
}
}
答案 0 :(得分:3)
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());
}
}