Refactoring a class using ArrayList to use HashMap (Java)
I was told to change everything to HashMap() instead of ArrayList() and for the most part everything worked perfect. However, I am having a problem getting this one method to work properly.
my HashMap() looks like
private HashMap critMap = new HashMap();
I have Room class and Creature class Room can have Creatures in it. The Creatures need to be able to react to certain commands which I already have methods for and should work as long as this method is right.开发者_开发知识库 I'm not certain to what is wrong.
This is the method with ArrayList()
public void critReactRoomStateChange2(String command, PC pc, String name) {
Creature temp = null;
for (int i = 0; i < critArr.size(); i++) {
if (!(getCreatures().get(i) instanceof PC) && !(getCreatures().get(i).getName().equals(name))) {
temp = getCreatures().get(i);
if (temp != null) {
getCreatures().get(i).reactStateChange(command, pc);
temp.checkNewRoom();
if (!temp.equals(getCreatures().get(i))) {
i--;
}
}
}
}
}
THIS IS THE METHOD AFTER I TIRED TO IMPLEMENT HashMap()
public void critReactRoomStateChange(String command, PC pc, String name) {
Creature temp = null;
if (!(getCreatures().get(name) instanceof PC)) {
temp = getCreatures().get(name);
if (temp != null) {
getCreatures().get(name).reactStateChange(command, pc);
temp.checkNewRoom();
}
}
}
the getCreatures().get(name) is taking the String name that is passed to it as a key of the hashMap to find the actual object it is referring to. As stated above my hashMap is thus the creatures name is the String(key) and the value Creature(contains other information other than name) is the value. When I call getCreature().get(name) I am looking for the Key String name and I want it to return the object Creature. If it cannot find it in the hashMap it should return null unless I'm mistaken.
I might just be missing something really simple. Any help would be greatly appreciated. If more code is needed I'd gladly edit this and put it in.
ThanksEdit: Creature class is a is abstract and PC, Animal, NPC all extend it. Just so your not wondering what the random PC and NPC and Animals are doing. lol
Edit2: No error besides that I'm not getting the reactions. It does nothing so critReactRoomStateChange is not working now. The Creatures are not getting passed along so the other methods can act on it.
So the 2nd box of code isn't working properly. It does nothing essentially.
I see that when you were using an ArrayList you applied the method getCreatures().get(i). It could be that you didn't change the getCreatures() method after you switched to HashMap since after the change you dont need to loop and get(i).
精彩评论