I am trying to use a HashMap
in my Java game to store Entity
's in a Stage
class and update them all. I am doing this so I can hopefully identify exactly what object is where with a key. I want it to find the key itself as well though, here is my code.
public class Stage {
private HashMap<String, Entity> entityHash = new HashMap<String, Entity>();
public Stage(){
}
public void addToStage(Entity e){
entityHash.put(e.getKey(), e);
}
public void test(){
for(int i = 0; i < entityHash.size(); i++){
//Line to be discussed about
System.out.println(entityHash.get("player").getPosition());
}
}
}
In the line of code I marked above to be discussed, is there a way for the code to find the key by itself. Every entity has a method called getKey()
and I want to know if I can get it somehow.
Note: I could easily do this by having an ArrayList
of strings for the keys and loop through that way, but I am hoping someone has an easier way of doing this that maybe I am missing. Thanks!