Kirs Kringle
Kirs Kringle

Reputation: 929

How would I change this method to work with an ArrayList?

public void critReactRoomStateChange(String command, PC pc, String name) {
    Creature temp = null;
    for (int i = 0; i < getCount(); i++) {
        if (!(getCreatures()[i] instanceof PC) && !(getCreatures()[i].getName().equals(name))) {
            temp = getCreatures()[i];
            if (temp != null) {
                getCreatures()[i].reactStateChange(command, pc);
                temp.checkNewRoom();
                if (!temp.equals(getCreatures()[i])) {
                    i--;
                }
            }
        }
    }
}

So I switched from having a private Creature[] creatures;
array to having a

private ArrayList<Creature> critArr = new ArrayList<Creature>();

ArrayList

I have changed the getCreatures() method to public ArrayList getCreatures() { return this.critArr; }

The count will not be needed as that is just critArr.size().

If more details are needed please let me know.
Basic structure of my program Room Class -holds creatures Creature Class -defines creatures

so pretty much a Room can have Creatures in it. I have multiple rooms that are set up and connected to each other through a simple interface of north, east, west, south. Not needed information, but this allows you to understand the point. Thanks for any help.

Upvotes: 0

Views: 176

Answers (3)

wolfcastle
wolfcastle

Reputation: 5930

With collections, it is generally good practise to make use of the enhanced for loop.

public void critReactRoomStateChange(String command, PC pc, String name) {
    List<Creature> creatures = getCreatures();
    for (Creature c : creatures) {
        if (!(c instanceof PC) && !(c.getName().equals(name))) {
                c.reactStateChange(command, pc);
                c.checkNewRoom();
//                    if (!temp.equals(c)) {
//                        i--;
//                    }
        }
    }
}

Notice how much shorter the code is without all of those getCreatures()[i] calls all over the place. I also dropped the null check, as it is redundant. instanceof already covers this.

Edit The reduced code also helps highlight a likely bug. The check for !temp.equals(getCreatures()[i]) doesn't make sense because you are comparing the same objects always. I have no idea what your intention was in decrementing the loop index to revisit the previous node. Generally, it is very unusual to mess with the loop index like that in a for loop. With the enhanced for-loop, it is impossible; and that is very intentional.

Upvotes: 2

Bozho
Bozho

Reputation: 597106

  • index access in a List - list.get(idx)
  • .length is .size()
  • index assignment is list.set(idx, value) (but you usually use list.add(value))

That's about all you need to know to transition from an array to list.

Upvotes: 3

Bala R
Bala R

Reputation: 108957

Instead of

getCreatures()[i]

use

getCreatures().get(i)

Upvotes: 2

Related Questions