javahashmapuniqueidentifierunique-key

How to generate unique keys for a hashtable, and recycle deleted keys?


For example, I need 10 objects stored in the hashmap.

So it creates keys 1,2,3,4,5

Then when I'm finished with '3', it deletes the whole entry and key for '3'. Making that key able to re-used for new object mappings -if I run over, via integer overflow or something.

Thoughts?

public static HashMap <GameKey, GameState> myMap  = new HashMap<GameKey, GameState>();
int i=0;

public void MapNewGameState(Gamestate gs){

myMap.add(i, gameStateA);
i++;
}


myMap.remove("3");
//Now I want to be sure that my MapNewGameState function is able to eventually map a new GameState to the key "3" later on,  

this is more a question about if HashMaps can be used in this way.


Solution

  • As I understand it you propose a key-pool where you get a key and if you don't need it anymore you put it back into the pool? If so this doesnt really make much sense since it adds complexity to your code but no other benefits (usually you pool something thats expensive to create or hold). And usually you want to recycle the value not the key?

    To create truly (practical) unique keys use UUID.randomUUID(), whith this you don't have to worry about keys.