自定义数组适配器初始化错误

Error in initialization of custom array adapter

我正在尝试制作自定义列表视图。列表声明如下

List<DocRow> doctors = new ArrayList<>();

正在填充此列表。

我的自定义数组适配器位于单独的 class 中,其构造函数声明如下。

public class DocAdapter extends ArrayAdapter<DocRow>{
    Context context;
    int resource;
    ArrayList<DocRow> doctors;
    private LayoutInflater inflater;

    public DocAdapter(@NonNull Context context, @LayoutRes int resource, ArrayList<DocRow> doctors) {
        super(context, resource, doctors);
        this.context = context;
        this.resource = resource;
        this.doctors = doctors;
        inflater = LayoutInflater.from(context);
    }

现在在我的主 activity 中,我试图通过传递我的列表(这是一个有效参数)来创建一个新的自定义数组适配器,但它不被接受。 link使用列表创建和设置适配器的代码如下。

DocAdapter adapter = new DocAdapter(getApplicationContext(), R.layout.doc_row, doctors);
docList.setAdapter(adapter);

谁能解释一下这是什么问题?错误截图的link在上面。我尝试搜索此特定问题,但未能找到有效的解决方案。

将您的构造函数参数更改为 List 而不是 ArrayList,因为您在其中传递列表。

 List<DocRow> doctors;

 public DocAdapter(@NonNull Context context, @LayoutRes int resource, List<DocRow> doctors) {
        super(context, resource, doctors);
        this.context = context;
        this.resource = resource;
        this.doctors = doctors;
        inflater = LayoutInflater.from(context);
    }

正如@Tim 所指出的,这里有一些关于为什么需要这样做的细节。

When an instance is initialized, it may be initialized with one of its child classes but the object remains an instance of Super class only(Due to runtime polymorphism) and therefore the methods that consume this instance either expect super class or the instance should be casted to superclass before passing it on.

The easiest way to identify is to always look at the type on the left-hand side instead.

List a=new ArrayList();

In above example, the instance is actually an arraylist but it is of Type List.

父class的引用可以存储子class的对象,反之则不然。

在这里,在适配器的构造函数中,您将 ArrayList<DocRow> 作为参数类型,但 doctors 列表的类型为 List<DocRow>。你,你正在将一个 List<> 对象传递给一个 ArrayList<> 引用。

要解决它,请将您的医生变量类型更改为 ArrayList<>,或者将您的构造函数参数类型更改为 List<>