burlap
burlap copied to clipboard
Renaming objects in a GenericOOState changes the order in objectsByClass list
This is a small thing, but I think it goes against the abstraction paradigm. Basically, I wanted to rename all the objects of a certain class, but that method just returns a reference to the list itself. However when you call state.renameObject(oldName, newName) it performs a removeObject and addObject so it changes the order of objects when iterating through that list. Below is my old code. The fix for me was simple, just create a shallow copy of that objectsList, but I'm not sure that's how it should be intended to do this sort of thing.
Wrong code:
List<ObjectInstance> agentObjects = state.objectsOfClass(GridGame.CLASS_AGENT);
for (int i = 0; i < agentObjects.size(); i++) {
ObjectInstance agentObject = agentObjects.get(i);
state = state.renameObject(agentObject.name(), newAgentNames.get(i));
}
Fixed code:
List<ObjectInstance> agentObjects = new ArrayList<ObjectInstance>(state.objectsOfClass(GridGame.CLASS_AGENT));
for (int i = 0; i < agentObjects.size(); i++) {
ObjectInstance agentObject = agentObjects.get(i);
state = state.renameObject(agentObject.name(), newAgentNames.get(i));
}