I've got a HashMap<Point, T>
data structure which holds several points that are mapped to other instances of the class T
. This map is given some default values when my class is instantiated like this:
T t1 = new T();
T t2 = new T();
Point p1 = new Point(0, 1);
Point p2 = new Point(0, 2);
HashMap<Point, T> map = new HashMap<Point, T>();
static {
map.put(p1, t1);
map.put(p2, t2);
}
In my code, I will be receiving events that contain an x
and an y
value. When I receive one of these events I'm trying to create a new Point
object with the x
and y
that is passed and then retrive the value from the map like this:
Point p = new Point(event.getX(), event.getY); // Assume (x, y) = (0, 1) (p1)
if(p.equals(p1)
T t = map.get(p);
Although p
is equal to p1
in this case (with (x, y) = (0, 1) I am getting a null
value back from the map
. I assume that is because the hashCode()
method in Point (Point2D)
uses something else than equals
to calculate an unique hash, which it should to prevent collisions.
My question is: How can I retrive the value from the map
using the new instance p
? Is there another data structure that would fit the use case?
I guess I could use toString()
or some other mapping like HashMap<String, T>
or perhaps I would extend the Point
class and Override
the hashCode()
method to suit my purposes. These ways feel "hacky" though, if there is a cleaner way I'd love to hear it.