0
public class Depot extends Item2
{
}

public class Station extends Item2
{
}

private final HashMap<Integer, Depot> depots = new HashMap<>();
private final HashMap<Integer, Station> stations = new HashMap<>();

both depots and stations stores something which has Item2 base. Now I want to pass to a function those:

Item2 item;
canBeAdded(item, depots);
canBeAdded(item, stations);

private boolean canBeAdded (Item2 item, HashMap<Integer, Item2> items)
{

sadly its not good, at canBeAdded it says

"Incompatible types: HashMap <Integer, Depot> cannot be converted to <Integer, Item2>"

John Smith
  • 6,129
  • 12
  • 68
  • 123

2 Answers2

4

You could use generic wild card here.

E.g:

private boolean canBeAdded(Item2 item, HashMap<Integer, ? extends Item2> items) {

For more info, Please visit these threads : Java Generics (Wildcards) and When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

Community
  • 1
  • 1
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
1

Change your signature to this:

private static boolean canBeAdded(Item2 item, HashMap<Integer, ? extends Item2> items) {

HashMap<Integer, Depot> is not a sub class of HashMap<Integer, Item2> but you can specify that any sub class is allowed like that ("wildcard"). Making it less specified it you need to use it though of course.

Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49