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>)
user2233440
  • 155
  • 2
  • 8
  • 2
    I think that WrenchDao should return List extends Part> – user2147970 Apr 15 '13 at 15:32
  • Can you paste the actual error? I think it's complaining that you can't cast `List` to `List`, not that you can't cast `Wrench` to `Part`... ? – Edward Thomson Apr 15 '13 at 15:35
  • What if instead of Part being the interface, you make it the parent class and then have Wrench and Hammer extend Part. You could even make getName() and getId() abstract so that Wrench and Hammer have to implement those methods. – RyPope Apr 15 '13 at 15:35
  • I wish I could change that but I am using a pre-built jar datamanager plugin. @EdwardThomson updating my question with error. – user2233440 Apr 15 '13 at 15:36

1 Answers1

14

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?

Community
  • 1
  • 1
Christian Fruth
  • 171
  • 1
  • 4