Get a list of a player's non-null inventory items?

Discussion in 'Plugin Development' started by tangster132, Nov 6, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    tangster132

    Hi guys.

    As the title says, is there a good way to get a list of a player's non-null inventory items? I would normally do something like:
    Code:
    ItemStack[] inventory = player.getInventory().getContents();
    ArrayList<ItemStack> items = new ArrayList<ItemStack>();
    for(ItemStack i : inventory){
        if(i != null)
            items.add(i);
    }
    
    However, I will be doing this multiple times, and it seems kind of wasteful having to loop through the entire inventory every single time. Is there a better way to do this?
     
  2. Offline

    TheCodingCat

    create a method in your class such as this one and call it when you need to
    Code:java
    1. public List<ItemStack> getContents(Player player) {
    2. List<ItemStack> stack = new ArrayList<ItemStack>();
    3. for (ItemStack i : player.getInventory().getContents()) {
    4. if (i != null) {
    5. stack.add(i);
    6. }
    7. }
    8. return stacks;
    9. }
     
  3. Offline

    tangster132

    Yeah, but you still have to iterate through the entire inventory whenever you call the method. I guess my main question is; is there a better way to do it without going through the whole inventory every single time?
     
Thread Status:
Not open for further replies.

Share This Page