Hi I got a question on whether to use an ArrayList or HashMap.
I am trying to build a Paint program.
Each drawn object will be assigned a unique object ID.
If I want a fast retrieval speed when I click on an object, should I be using an arraylist or hashmap?
In general hashmap has O(1) while arraylist has O(n) retrieval speed.
However, I think for my case, since when I click on an object, I’ll get the ID, hence the index of the array and I can do something like ArraylistObject.get(ithElement); , so in this case this will also be a O(1) retrieval process?
any inputs?
Thanks!
If objects have an ID that can be mapped 1-to-1 to an array than that will be O(1) access as well, and in practice will be slightly faster than a hashmap lookup (you don’t have to compute the hash).
However, the issue will be what happens when you delete an object. You will be left with a hole in the list. When creating new objects you can then keep appending to the list and leave it to get slowly more fragmented or try and find a spare slot in which case you’ll be doing an O(n) search for a spare space.
In short – a hashmap is probably more appropriate.