1

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!

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
Gad Wissberg
  • 455
  • 1
  • 6
  • 19
  • You could try having each object extend an abstract class that only has an enum and process each object based on the enum value. – M. Shaw Jul 12 '15 at 15:46
  • Forgot to mention, every object extends an abstract class I made called GameObject. But still, I want to have objects seperated by types. I just don't want to deal with massive number of references to arrays. – Gad Wissberg Jul 12 '15 at 15:54
  • Just make a field that's enum in `GameObject` and update each object after checking the value of the enum? – M. Shaw Jul 12 '15 at 16:01
  • possible duplicate of [HashMap get/put complexity](http://stackoverflow.com/questions/4553624/hashmap-get-put-complexity) – John Jul 12 '15 at 16:29
  • 1
    You may also like to look into entity component systems. LibGDX has its own, Ashley: https://github.com/libgdx/ashley – monkeyhybrid Jul 12 '15 at 20:26

1 Answers1

3

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

Yon Kornilov
  • 101
  • 4