ProHackr112 ProHackr112 - 1 year ago 57
Java Question

Java - Removing an object from an object array

I am writing a large program that involves an Object called

. 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);

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
isn't going to be used until much later in development. I have no way to see if
works. I modified a function I wrote called
to get this... Would
work? If not, why?

Answer Source

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.


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) {

    public static void main(String[] args) {
        // create a new instance
        Player player = new Player();
        // call a method on the instance
        player.addItem("bla", 0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download