gpt4 book ai didi

java - 抽象类和嵌套类的ArrayList冲突

转载 作者:行者123 更新时间:2023-11-29 08:23:12 26 4
gpt4 key购买 nike

我有一个适配器:

class PhotoAdapter : RecyclerView.Adapter<PhotoAdapter.AbstractViewHolder>() {

fun addItems(list: ArrayList<AbstractItem>) {
val position = items.size
items.addAll(list)
notifyItemRangeInserted(position, list.size)
}

abstract class AbstractItem(
open val id: Int
)

class PhotoItem(
override val id: Int,
val url: String?
) : AbstractItem(id)

...
}

以及使用它的片段:

val adapter = PhotoAdapter()
val list: ArrayList<PhotoAdapter.PhotoItem> = ArrayList(emptyList<PhotoAdapter.PhotoItem>())
adapter.addItems(list)

但是尽管 PhotoItem 嵌套自 AbstractItem 我无法编译:

enter image description here

如果我将 addItems() 中的 ArrayList 更改为简单的 List,它会编译:

fun addItems(list: List<AbstractItem>) {
...

可能类型转换也可以,但我没有检查。

enter image description here

问题是为什么实现(ArrayList)和接口(interface)(List)对嵌套类的看法不同?

更新

我重写成Java,会更清晰。

public class Adapter extends RecyclerView.Adapter<Adapter.AbstractViewHolder> {

private ArrayList<AbstractItem> items;

public void addItems(ArrayList<AbstractItem> list) {
int position = items.size();
items.addAll(list);
notifyItemRangeInserted(position, list.size());
}

abstract class AbstractViewHolder extends RecyclerView.ViewHolder {

public AbstractViewHolder(@NonNull View itemView) {
super(itemView);
}
}

public abstract class AbstractItem {
int id;
}

public class PhotoItem extends AbstractItem {
int id;
String url;
}
}

public class Example {

void init() {
ArrayList<Adapter.PhotoItem> list = new ArrayList<>();
Adapter adapter = new Adapter();
adapter.addItems(list);
}
}

enter image description here

最佳答案

因为 List是协变的(它被定义为 List<out T> ),所以 List<PhotoAdapter.PhotoItem>List<AbstractItem> 的子类型.但是MutableListArrayList是不变的,这意味着 ArrayList<PhotoAdapter.PhotoItem>不是 ArrayList<AbstractItem> 的子类型(或父类(super class)型) .

参见 https://kotlinlang.org/docs/reference/generics.html#variance详细解释为什么(我认为在这里复制它没有多大意义)。

关于java - 抽象类和嵌套类的ArrayList冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55759839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com