List<ItemStack> vanishing when saving into another List

Discussion in 'Spigot Plugin Development' started by Adenor, Oct 9, 2019.

  1. Hello there fellow Spigoters,

    I'm creating a DeathChest plugin but can't figure out why my items are not beeing saved.

    When dieing, I create a new objective called DeathChest, where the following is saved:
    Code (Java):
    package at.rengobli.deathchest.deathchest;

    import java.util.List;
    import java.util.UUID;

    import org.bukkit.Location;
    import org.bukkit.inventory.ItemStack;

    public class DeathChest {

        private Location loc;
        private UUID owner;
        private List<ItemStack> items;

        public DeathChest(Location loc, UUID owner, List<ItemStack> items) {
            this.loc = loc;
            this.owner = owner;
            this.items = items;
        }

        public Location getLocation() {
            return loc;
        }

        public UUID getOwner() {
            return owner;
        }

        public List<ItemStack> getItems() {
            return items;
        }

    }
     
    My Manager class now saves it:
    Code (Java):
    private List<DeathChest> chests;

        public List<DeathChest> getDeathChests() {
            return chests;
        }

        public DeathChestManager() {
            this.chests = new ArrayList<>();
            this.chests.clear();

        }

    public void createDeathChest(Player p, Location loc, List<ItemStack> items) {
            this.chests.add(new DeathChest(loc, p.getUniqueId(), items));
    }

     
    So far, everything works as it should.

    The problem:
    When getting a DeathChest, I can perfectly get the Location and owner name - but the items are always empty?

    I tried debuging and found out that the items ARE being saved, but as soon as it is saved into the List<DeathChest> chests, the items seem to disappear.

    I dunno why, but everything else is getting saved perfectly fine.

    Thanks for reading,
    Markus
     
  2. Here
    Code (Java):
    public DeathChest(Location loc, UUID owner, List<ItemStack> items) {
            this.loc = loc;
            this.owner = owner;
            this.items = items;
        }
    You are only passing a reference of items object instead of copying it. Try this:

    Code (Java):
    this.items = new ArrayList<ItemStack>(items);
     
    • Winner Winner x 1
  3. It works! Thanks :)
     
  4. Or you could use guavas method
    Lists.newArrayList(items);