-3

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!

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Pookie
  • 1,239
  • 1
  • 14
  • 44

1 Answers1

0

Maps have a method that returns the set of keys used it's called keySet().

You can iterate over it like this:

public void test(){
    for(String key : entityHash.keySet()){
        System.out.println(entityHash.get(key).getPosition());
    }
}
JoeyJubb
  • 2,341
  • 1
  • 12
  • 19
  • This helped a ton thank you so much, I will accept answer as soon as I can! Thank you! – Pookie May 24 '16 at 08:18
  • 1
    It would be preferable to use `entrySet()`, which permits to loop directly over the entries, instead of looping over the keys and retrieving value. Better yet: loop directly over the values with `values()`, since the OP isn't interested in the key. – Tunaki May 24 '16 at 08:40