0

Say I've got a Java file with 500 custom objects of type Item. Now, say I want users to be able to add/remove any one of those objects to that list in the program. I want to try to avoid doing something like this:

public class Inventory {
    public static ArrayList<Item> inv = new ArrayList<>();
    public static void addItem1 {
        inv.add(Item.Item1); //Pulling from Item class
    } //addItem1()
    public static void removeItem1 {
        inv.remove(Item.Item1);
    } //removeItem1()
    public static void addItem 2 {
        . . .
    }
    . . .
}

By doing that, I'd have to make an add and a remove function for every single item. There will be hundreds of items, so I sincerely hope there's a better way for the user to be able to do so from inside of the program. This would further be awful because of how it would require some massive nested switch statements to swap out everything.

Instead I'd hope to implement a single adder method and a single remover method, that could take the user's input (a String with the literal name of the Item they are trying to add), and somehow find/select the Item. Implementation thoughts?

5
  • Maybe use a field? Commented Dec 2, 2017 at 0:17
  • 1
    what is the difference between Item1 and Item2 and so on? just the name???? Commented Dec 2, 2017 at 0:21
  • By the way, use List rather than ArrayList unless absolutely necessary Commented Dec 2, 2017 at 0:53
  • 1
    RAZ makes a good point. Are these items all different classes? If they are, why can't your make all of them extend some superclass of (superitem :P) and then operate on that superclass? Commented Dec 2, 2017 at 0:55
  • @RAZ_Muh_Taz, @ifly6; these items are all similar, in that they hold at least those three base variables, though they may have more. For example, a sword is an item and a candle is an item; each have a name, price, and description, though the sword will have additional values. Commented Dec 2, 2017 at 22:40

2 Answers 2

2

How about using generic class ?

public class Inventory<T> {
public static ArrayList<Item> inv = new ArrayList<>();
public void addItem (T item){
    inv.add((Item)item); // where item can be anything from Item.item1 to Item.item500
}
public void removeItem (T item){
    inv.remove((Item)item);
}

In that case, to see if your item is in fact an item do something similar to this: System.out.println(item.getClass().getName()); //should return Item

Sign up to request clarification or add additional context in comments.

Comments

0

Perhaps use:

public void setItem(Item item){
    inv.add(item);
}

Then use the same concept for removal.

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.