0

I have an inventory class that has an array of the class 'Item', called items. Within the Item class, I have an int called quantity to represent how many of the item that you get with each pickup. I haven't been able to figure out how to get the number of duplicate items within the array, so that I can multiply that by the getQuantity() method for that item and get the total quantity of the item that the player is carrying.

public class Inventory {


    private Item[] items;   //A private Item array, called items
    private int firstFree;
    private int quantity;
    private WorldRenderer world;


    /**
     * CREATES THE INVENTORY AT A SIZE SPECIFIED IN THE PARATHENESIS
     */
    public Inventory(int size) {
        items = new Item[size];
        firstFree = 0;
    }


    public int getItemCount() {
        for (int i = firstFree; i < items.length; i++) {
            if (items[i] != null) {
                return items.length;
            }
        }
        return 0;
    }

    public boolean add(Item item) {
        if (firstFree == items.length) {
            return false;
        }
        items[firstFree] = item;

        for (int i = firstFree; i < items.length; i++)
            if (items[i] == null) {
                firstFree = i;
                return true;
            }
        firstFree = items.length;

        return true;


        /**for (int i = 0; i < items.length; i++)
         if (items[i] == null){
         items[i] = item;
         System.out.println("Item " + item.getName() + " added to inventory at index " + i);  // TESTING 
         return true;
         }
         return false;
         }**/
    }

    public Item get(int index) {
        return items[index];
    }

    public void setQuantity(Item item, int quantity) {
        for (int i = 0; i < items.length; i++) {
            if (items[i] == item) {
                items[i].setQuantity(quantity);
            }
        }
    }

    public void removeQuantity(Item item, int quantity) {
        for (int i = 0; i < items.length; i++) {
            if (items[i] == item) {
                items[i].setQuantity(item.getQuantity() - quantity);
            }
        }

    }

    public int getQuantity(Item item) {
        int quantity = 0;
        for (int i = 0; i < items.length; i++) {
            if (items[i] == item) {
                quantity = items[i].getQuantity();
            }
        }
        return quantity;
    }
}

Perhaps there is a better way to go about creating an inventory for my particular problem?

EDIT: Trying the HashMap and getting an NPE at this line

     if (items.containsKey(item)){
        Integer previousQuantity = items.get(items);
        items.put(item,  ++previousQuantity); // NPE this line.
    } else {
        items.put(item,  1);
    }
7
  • Does changing your code to quantity += items[i].getQuantity(); produce the expected result? If not, what is the expected result and what result are you currently getting? Commented Sep 23, 2013 at 17:05
  • How do you know if an Item is a duplicate? You don't seem to have any fields in place (such as a string with the name of the Item) that could make that determination. Commented Sep 23, 2013 at 17:22
  • You may find it useful to verbalise the problem in non-code first. Then convert that into pseudo code. Doing so might help you understand the logic required to a,choice your goal. In the meantime some thoughts: What makes an Item a duplicate? Your setQuantity and removeQuantity methods are testing if it is the same instance, is that correct? Your getItemCount will return the total array size or 0 only Commented Sep 23, 2013 at 17:37
  • Thanks for the quick responses guys, I'm not where I can get into Eclipse right now, at work :(. @musical_coder I have a string 'name' within my GameObject class, which is what my Item class extends. I've tried to find the amount by using .equalsIgnoringCase but I'm probably doing it wrong. Commented Sep 23, 2013 at 18:34
  • @Tanis.7x will try that also, and you're too Romski Commented Sep 23, 2013 at 18:34

3 Answers 3

3

Rather than Item[] items you might consider HashMap<Item, Integer> items where the Integer refers to quantity.

This would make sure that there are no duplicate Items as well as simplify finding the quantity.

Example:

import java.util.HashMap;

public class Inventory {

    private HashMap<Item, Integer> items;
    private int maxSize;

    public Inventory(int maxSize) {
        this.maxSize = maxSize;
        items = new HashMap<Item, Integer>();
    }

    public int getItemCount() {
        int count = 0;
        for (Item item: items.keySet()){
            count += items.get(item);
        }
        return count;
    }

    public boolean add(Item item) {
        if (items.size() >= maxSize){
            return false;
        }

        if (items.containsKey(item)){
            Integer previousQuantity = items.get(items);
            items.put(item,  ++previousQuantity);
        } else {
            items.put(item,  1);
        }

        return true;
    }
}

Generic Implementation of equals() and hashCode():

public class Item {
    int itemType;

    @Override
    public boolean equals(Object o) {
        if (this == o) { return true; }
        if (o == null || getClass() != o.getClass()) { return false;  }

        Item item = (Item) o;
        if (itemType != item.itemType) { return false; }

        return true;
    }

    @Override
    public int hashCode() {
        return itemType;
    }
}
Sign up to request clarification or add additional context in comments.

9 Comments

This assumes that your Item class hash a functional equals() method.
thanks for the info, I think that I'd like to try this, seems it would simplify things quite a bit. But what do you mean by my Item class having a functional equals() method. I have an int called Type within GameObject (Item extends GO), so I can create Item 'types', will that work?
The get method on HashMap uses equals() for retrieving the Item. You will also need to override the hashCode() method. You might want to read up on java hashcode and equals methods.
@AspiretoCode Basically, if you don't override the equals method, you might end up with duplicates Items in your items list.
As I was reading your question @AspiretoCode I was thinking HashMap the whole time. I'm glad someone else suggested it, it's the right way to do this. It will also make item lookup much more straightforward and fast.
|
0

you can find out number of unique item by using Set. In Set no item is repeated. So if you can convert your array to set then you can find the number of unique item. And you can get the number of repeated item by subtracting from the total item. to convet array to Set you have to do

Set<Integer> uniqueItem = new HashSet<Integer>(Arrays.asList(items));
int total_repeated_item=items.length-uniqueItem.size();

Comments

0

You probably need a unique ID to differentiate between items in you inventory, you can then put that in a Map which can just take care of counting duplicates for you . In your case the name of the item can be the unique identifier (Which would be the key in the Map) .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.