类扩展类的适配器

时间:2018-01-31 18:09:49

标签: java android

我有类对象Student,Teacher,Worker扩展类对象People。现在,我想编写一个可用于所有类的适配器。我尝试过使用ArrayAdapter <People>但是在传递给Student数组时发生了错误。 enter image description here

public class AdapterPeople extends ArrayAdapter<People> {
private ArrayList<People> arrPeople;
private Context context;
private LayoutInflater layoutInflater;

public AdapterPeople(@NonNull Context context, int resource, @NonNull ArrayList<People> objects) {
    super(context, resource, objects);
    this.arrPeople = objects;
    this.context = context;
    this.layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}

1 个答案:

答案 0 :(得分:2)

ArrayList<People>ArrayList<Student>

不同

因此您可以使用通配符?

public class AdapterPeople extends ArrayAdapter<People> {
    private ArrayList<? extends People> arrPeople;
    private Context context;
    private LayoutInflater layoutInflater;

    public AdapterPeople(@NonNull Context context, int resource, @NonNull ArrayList<? extends People> objects) {
        super(context, resource, objects);
        this.arrPeople = objects;
        this.context = context;
        this.layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    }

证明

Generics, Inheritance, and Subtypes

解决方案参考

Upper Bounded Wildcards