5

I have:

class Hammer Implements Part {
    public String getName() { return name; }
    public int getId() { return id; }
    ...
}

class Wrench implements Part {
    public String getName() { return name; }
    public int getId() { return id; }
    ...
}

interface Part {
    String getName();
    int getId();
}

I am using a prebuilt database manager written for Android SQLite that returns a list of Objects based on what I am retrieving:

dataManager().getWrenchDao().getAll(); // returns List<Wrench>

I cannot change how this function operates.

Now I am getting both lists like:

List<Wrench> wrenches = dataManager().getWrenchDao().getAll();
List<Hammer> hammers = dataManager().getHammerDao().getAll();

However, I want to populate spinners with this data (Spinners are the drop down lists in android).

loadSpinner(Spinner s, List<Part> data) {
    ...
    data.ElementAt(i).getName();
    data.ElementAt(i).getId();
    ...
}

loadSpinner(wrenchSpinner, wrenches);

But it gives me a casting error that you cannot change Wrench to Part. Why doesn't Java let me do this? Wrenches have all methods that Parts do so why cant I cast it into something it implements and use it?

Error:

The method loadSpinner(Spinner, List<Part>) in the type NewActivity is not applicable for the arguments (Spinner, List<Wrench>)

You have to replace the second parameter of loadSpinner to:

loadSpinner(Spinner s, List<? extends Part> data)

See also: When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

4

1 回答 1

14

您必须将第二个参数替换loadSpinner为:

loadSpinner(Spinner s, List<? extends Part> data)

另请参阅:Java 泛型何时需要 <? 扩展 T> 而不是 <T> 并且切换有什么缺点吗?

于 2013-04-15T15:37:12.757 回答