Search code examples
javaandroidarrayslibgdx

Would HashMap provide efficient access to object arrays by a string type?


I'm working on a game and I got the Main class which holds a number of object references arrays.

In the main class, I loop through every array and update the objects. The problem is that I have to hold an array for each type of object. It's comfortable to have an array for each type but it'd make the code ugly when I'll have dozens of types.

I thought about having a HashMap of String|Array, and every entry would have the object type name (String) and the array itself. Every object extends an abstract class I made called GameObject. My question is that efficient to work with hashmap? (meaning in every loop the Main class gets an array from the map and runs through it's objects.) By efficient I mean if HashMap's "get" method can slow down things.

Or maybe there are better solutions for holding lots of objects with different types?

I'm developing the game in Java, to Android, using LibGDX. Thank you!


Solution

  • HashMap's get method is very efficient because it uses a hash table. In the case of the map key being a String object, the value of the string is run through a hash function. The result is used to index a "bucket" where the reference to the key is stored.

    With a good hash function for the object, each unique state of the object will have it's own bucket. So calling get(key) on the HashMap will instantly give you the reference to the key's value.

    String's hashcode method is already implemented and produced a unique hash for each state of String.

    What this means:

    If you have a unique String value, you will get instant access to the value using HashMap's get method.

    The same is not true for TreeMap or TreeSet, which are meant for having an ordered map or set.

    See: https://en.m.wikipedia.org/wiki/Hash_table