Java casting a list of <object> to its interface

casting, generics, inheritance, interface, java

Solution

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?

Problem

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>) ```

Original source

Related problems