javadata-structureshashmapvalue-class

What data structure should I use for lookup in constant time from a changing pair of values to an object in java?


I have a valueclass (position) with two doubles (x and y) in it. I also have a class ship that has an attribute with a position object in it.

I need to be able to do do a lookup like: get ship at (5,7) with constant time. I also want to be able to change the value of a position object because multiple ships can refer to the same position objects and they all have to move together when that position object changes.

I have looked at hashmap, but to be able to do get ship at new Position(5,7) I need to override the hashcode of the position object (so that positions with the same values have the same hash), and I heard you shouldn't change the hashcode of an object in a hashlist.


Solution

  • This might not be exactly what you are looking for but I think what you need is a 2D spatial partitioning data structure like a quad-tree.