0

I am making a game in which i want to make an array called "Inventory" in which I want to be able to store different types of objects of different classes (such as weapons, bottles, food items )

I want to know how this is possible... arraylist can make only arrays of one type...I tried that too.

thanks in advance.

3
  • If your classes implement one common interface (or if they extend one common class), you may declare an array of this common class/interface. Otherwise, Object is the answer.. Commented Jan 19, 2015 at 15:08
  • Make all of your items extend some super class (Item, perhaps) that defines methods inherent to any item. Because each type of item would extend Item, you could then use List<Item>, or Item[] to store all of your items. Commented Jan 19, 2015 at 15:08
  • You can use an Object[] if you need to. My recommendation is to make 1 item class, called Item. Then you can have other classes extend it. Then make an Item[]. Commented Jan 19, 2015 at 15:09

3 Answers 3

3

Let your objects extend a superclass like Item and make an Item[] array.

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

Comments

0

You'll have to use an array of a common superclass/interface.

The easiest thing would be to use an array of Object (Object[]), but that includes the risk to add literally anything.

It'd be best if you make an interface that all your objects are going to implement - even if it has to be a tag interface - thus limiting the kind of objects than can be putted there. Of course, if there is common functionalities of those objects (such as attributes like "weights" or methods as "drawObject"), the interface actually has some meaning beyond the tag

Comments

0

Have all your classes of items implement the same interface, "Item". Then make the arraylist of type Item.

Or, if the items have common data (such as price) you could have them all extend the same class.

Example of extending the same abstract class:

public abstract class Item {
    private int value;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}

public class Weapon extends Item {
    private int damage;

    public Weapon(int value, int damage) {
        this.setValue(value);
        this.damage = damage;
    }
}

ArrayList declaration:

List<Item> inventory = new ArrayList<Item>();
inventory.add(new Weapon(10, 25));

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.