How to add to a List from a method

Sorry coming from C# here and getting a little confused.

I have a declaration as follows:

 private final HashMap<String, List<? extends Item>> inventory = new HashMap<>();

The inventory is divided into different classifications. For example Weapons. So we have a class Weapon extends Item.

Now I have a method to add a weapon.

  public void addWeapon(Weapon weapon) {
    inventory.get("weapons").add(weapon);
  }

This is where I hit a problem, saying the ? extends Item expected.

Any help, or a pointer to an answer appreciated.

Answer

your value is a List, but your adding a Weapon not a List of them, or a list of Item’s, this should work:

private final HashMap<String, List<Item>> inventory = new HashMap<>();

public void addWeapon(Weapon weapon) {
    inventory.get("weapons").add(weapon);
}

Leave a Reply

Your email address will not be published. Required fields are marked *