1

继承和泛型的新手,如果我的问题很愚蠢,请多多包涵:

我有以下内容:

public abstract class car {
    private long id;
    private String name;

    public car (long id, String name) {
        this.id = id;
        this.name = name;
    }

    public final long getID(){
        return id;
    }

    public final String getName(){
        return name;
    }
}

public class sedan extends car {
    public sedan(long id, String name) {
        super (id, name);
    }
    ...
}

public class jeep extends car {
    public jeep(long id, String name) {
        super (id, name);
    }
    ...
}

我正在尝试为微调器扩展 ArrayAdapter,如下所示:

public class DropdownAdapter extends ArrayAdapter<car> {
    private Context context;
    private List<car> values;

    public DropdownAdapter(Context context, int textViewResourceId, List<car> values) {
        super(context, textViewResourceId, values);
        this.context = context;
        this.values = values;
    }
    ...
}

当我尝试使用它时,问题就来了:

adapter = new DropdownAdapter (this, android.R.layout.simple_spinner_item, lstSedan);

会给我错误:构造函数 DropdownAdapter (ScreenItemList, int, List< 轿车 >) 未定义

adapter = new DropdownAdapter (this, android.R.layout.simple_spinner_item, lstJeep);

会给我错误:构造函数 DropdownAdapter (ScreenItemList, int, List< jeep >) is undefined

这里有什么问题?当 lstSedan 或 lstJeep 从汽车派生时,为什么我不能使用它们作为参数?我该如何解决这个问题?谢谢!

4

2 回答 2

2

您定义了一个需要类型参数的方法List<a>

  public SpinnerAdapter(Context context, int textViewResourceId, List<a> values)

也就是说,它需要一个类型为的项目列表a。但是你传递了一个类型b为继承a的参数,而不是一个类型的参数List<b> 尝试使用这种方式:

  List<b> lstB= new ArrayList<b>();
  adapter = new SpinnerAdapter (this, android.R.layout.simple_spinner_item, lstB);

正如 JoxTraex 所说,您应该阅读java 名称约定

更新
对不起,我犯了一个错误。因为 java 不允许将List<ChildClass>参数传递给List<ParentClass>,所以在这种情况下你不应该使用继承。尝试使用泛型

public class DropdownAdapter extends ArrayAdapter<T> {
private Context context;
private List<T> values;

public DropdownAdapter(Context context, int textViewResourceId, List<T> values) {
    super(context, textViewResourceId, values);
    this.context = context;
    this.values = values;
}
...
}

这个函数调用应该可以工作:

 adapter = new SpinnerAdapter (this, android.R.layout.simple_spinner_item, lstB);
于 2012-08-15T04:42:41.093 回答
0

原因是您拥有它的名称,特别是 SDK 中已经存在SpinnerAdapter。您需要明确说明您正在使用哪一个或更改类名。

建议

另外仅供参考,您不应该将类称为 A 之类的无用名称。

于 2012-08-15T03:27:44.717 回答