开发者

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

开发者 https://www.devze.com 2023-02-26 21:07 出处:网络
public void critReactRoomStateChange(String command, PC pc, String name) { Creature temp = null; for (int i = 0; i < getCount(); i++) {
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 (!te开发者_高级运维mp.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.


  • 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.


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.


Instead of

getCreatures()[i]

use

getCreatures().get(i)
0

精彩评论

暂无评论...
验证码 换一张
取 消