Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java casting a list of <object> to its interface

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>)
like image 547
user2233440 Avatar asked Apr 15 '13 15:04

user2233440


1 Answers

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?

like image 152
Christian Fruth Avatar answered Oct 14 '22 22:10

Christian Fruth