Solved Grabbing an ItemStack from a HashMap alters the original item?

Discussion in 'Spigot Plugin Development' started by SuperRonanCraft, Jun 6, 2017.

  1. I'm attempting to load up an item from a file, then making a copy of that item and alter the name and lore as it prints out. But it only works once, after that the original item in the HashMap turns into the item I just altered. Any ideas why this keeps happening? I'm trying to lower the amount of processes my plugin does by only loading up the menu once and then just alter the item as the plugin prints it out to replace placeholders and such. Here's part of my code that i'm having issues with.
    Code (Text):
    HashMap<String, ItemStack> item = new HashMap<String, ItemStack>();
    String[] sections = {"World" , "Kills", "Deaths", "Fly", "Sneaking"};
    private void loadItems() {
            for (String str : sections) {
                String[] item = menu.getString(str + ".Item").split(":");
                String name = menu.getString(str + ".Name");
                List<String> lore = menu.getStringList(str + ".Lore");
                ItemStack mat = phd.getItem(item, name, lore);
                this.item.put(str, mat);
    public void create(Player player) {
            Inventory inv = Bukkit.createInventory(null, 9, "Test");
            for (int i = 0; i < sections.length; i++) {
                ItemStack mat = item.get(sections[i]); //<-- Keeps altering the HashMap :(
                inv.setItem(i, mat);
    #1 SuperRonanCraft, Jun 6, 2017
    Last edited: Jun 6, 2017
  2. you don't have an error with this code?
    Code (Java):
    String item = menu.getString(str + ".Item").split(":");
  3. my bad, didn't copy it directly, meant to put "String[]" but nope, it just keeps altering the darn hashmap, or something, not sure
  4. You will need one new item per player. One item per player is not too heavy and it is necessary in this case.

    change the problematic line to:
    Code (Text):
    ItemStack mat = new ItemStack(item.get(sections[i]));
    Or use clone()
  5. when you used item[1, 2, 3] and more and also what is
    Code (Java):
    checkPlaceholders(mat, ticketID, -1);
  6. That part is secret as it's part of my premium resource, but I think Niki got it :)
    Dang, that is so true, I forgot you needed a new item per player, thank you so much, sometimes the simple things are what get me :D
  7. For future reference, this is the difference between mutable and immutable objects. ;)
  8. Code (Text):
    for (int i = 0; i < sections.length; i++) {
                ItemStack mat = item.get(sections[i]).clone(); //<-- Doesn't alter the HashMap :D
                inv.setItem(i, mat);
  9. I'm sure it is been said above already and already marked as solved