Inventory API

I am trying to loop over every ItemStack in the player’s inventory (Including but not limited to armor slots, slots from mods, the crafting slots, etc) , and repair it.

What I am trying:

Iterator<Inventory> inv = p.getInventory().iterator();
    while(inv.hasNext()) {
        Inventory stack = inv.next();
        //WUT? The iterator "returns" an inventory???
    }
}
  • Why does it return an inventory?
  • What is the correct way to do this?

Really, the only time you should be using an Iterator is if you’re planning on removing an object and want to avoid a ConcurrentModificationException. If you’re not planning on removing anything, you can more easily use:

for (Inventory inventory : p.getInventory()) {
    // Something
}

However, that’s a bit off-base for what you’re asking. Why does Iterator<?> return an Inventory object? I’d recommend reading a tutorial on how Generics work.

If your question is “Why does the inventory iterate more inventories?”, I’d recommend reading the long-ago accepted Queryable Unified Inventory API PR that was put together by @mumfrey .

1 Like

Why does the inventory iterate more inventories?

Yep that was my question I asked it a bit wrong, reading it now.

Would this work?

Edit: I could not find what kind of inventories it “iterates” (idk how it is called in a for statement) over. Are it all it’s childs or are it all one-stack inventories?

No idea! :smiley:

@gabizou ?

Inventories are containers for sub-inventories. You can do a deep recursion to get all the leaf nodes.
This is my response to another thread:

private Iterable<Slot> getSlots(Inventory inventory) {
    if (inventory instanceof Slot) {
        return Collections.emptyList();
    }
    Iterable<Slot> slots = inventory.slots();
    for (Inventory subInventory : inventory) {
        Iterables.concat(slots, getSlots(subInventory));
    }
    return slots;
}
1 Like