1.14.4 Player's inventory removeItem() method

Discussion in 'Spigot Plugin Development' started by Ardno, Jan 22, 2020.

  1. Hello,
    I'm making a TokensBank plugin, but I have 1 problem. I want to remove count of tokens(items) from player's inventory. How to use method removeItem()? Or how to create HashMap<Integer ItemStack> what I will use in this method?
    Method constructor:
    Code (Java):
    @NotNull HashMap<Integer,ItemStack>    removeItem(@NotNull ItemStack... items)  
    Removes the given ItemStacks from the inventory.
  2. You don't need to create a HashMap, the method returns a HashMap.
    You pass as input arguments the ItemStacks (with given amounts). The method will try to remove 'as much as possible' from the types and amounts you give as arguments.
  3. Can you give me an example please? I'm lost in it
  4. Take this piece of code:
    Code (Java):
    final HashMap<Integer,ItemStack> integerItemStackHashMap = player.getInventory().removeItem(new ItemStack(Material.BAMBOO, 64), new ItemStack(Material.BAMBOO, 23));
    If I have no Bamboo in my Inventory, the HashMap will be:
    Code (Text):
    {0=ItemStack{BAMBOO x 64}, 1=ItemStack{BAMBOO x 64}}
    and I obviously have no Bamboo in my Inventory

    If I have one Stack & 16 Bamboo, the Map will contain these entries:
    Code (Text):
    {1=ItemStack{BAMBOO x 7}}
    and I have no Bamboo in my inventory

    If I have 2 Stacks of Bamboo in my Inventory, the Map will be empty and I have 41 Bamboo left in my inventory.

    As you can see, the function removes as much as possible and returns what it couldn't remove as well as the position in the initially given array
  5. So you should have a look at the API: Inventory#removeItem(ItemStack item) - this returns a HashMap with the Items it failed to remove. If it didn't fail to remove any, the HashMap will be empty.

    I would just use the Inventory#remove(ItemStack item), which will find the exact matching ItemStack in the inventory and remove it, if not found. Nothing happens.
  6. That was surprising...
    • Agree Agree x 1
  7. Oh wow yes indeed xD