I have a HashMap<Point, T> data structure that contains several points that are mapped to other instances of class T This map has some default values ββwhen an instance of my class is created, for example:
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 receive events containing the value of x and y . When I receive one of these events, I try to create a new Point object with missing x and y , and then extract the value from the map as follows:
Point p = new Point(event.getX(), event.getY);
Although in this case p is equal to p1 (with (x, y) = (0, 1), I get the null value from map . I assume that this is because the hashCode() method in Point (Point2D) uses something other than equals to compute a unique hash that should prevent collisions.
My question is: how can I get the value from map using a new instance of p ? Is there any other data structure that matches the usage scenario?
I think I could use toString() or some other mapping, for example HashMap<String, T> , or maybe I would extend the Point and Override class to hashCode() method in accordance with my goals. These methods feel βhackedβ, although if there is a cleaner way, I would like to hear it.
source share