ProHackr112 ProHackr112 - 5 months ago 8
Java Question

Java - Removing an object from an object array

I am writing a large program that involves an Object called

Player
. The Player definition is as follows:

public class Player
{
public static String name;
public static Item inventory[] = new Item[10];
public static int items;

/* ... */

public void addItem(String itemName, int itemType)
{
if ((items + 1) <= 10) {
inventory[items] = new Item(itemName, itemType);
items++;
}
}

public void removeItem(int x)
{
for (int i = x; i < items; i++)
inventory[i] = inventory[i+1];
}
}


I am adding inventory handling now because it's much easier than adding it later, but
inventory
isn't going to be used until much later in development. I have no way to see if
removeItem
works. I modified a function I wrote called
strstrip
to get this... Would
removeItem
work? If not, why?

Answer

Create unit tests for your classes especially if you going to build 'big and complicated program'. This will guarantee you that the code written will work later and if you change your code the failure of unit tests should indicate a problem. The unit test also gives you ability to check that your method works as expected.

As per other comments, consider using List interface instead of array, unless you have some specific requirement (I cannot imagine any). And definitely, having public static fields in your class looks suspicious.

EDIT

Just to indicate how code can look like and how to call methods from the main method.

public class Player {

    private String name;
    private List<Item> inventory;
    private int items;

    public Player() {
        this.inventory = new ArrayList();
    }

    public void addItem(String itemName, int itemType) {
        this.inventory.add(new Item(itemName, itemType));
    }

    public void removeItem(int x) {
        Item itemToRemove = this.inventory.get(x);
        if (itemToRemove != null) {
            this.inventory.remove(itemToRemove);
        }
    }

    public static void main(String[] args) {
        // create a new instance
        Player player = new Player();
        // call a method on the instance
        player.addItem("bla", 0);
    }
}
Comments