Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap get value of object that is "equal" but different hash?

Tags:

java

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.

like image 313
span Avatar asked Jan 29 '13 18:01

span


1 Answers

According to the Java documentation,

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

It appears that in your case two Point objects are equal (as per the equals method) but their hash codes are different. This means that you need to fix your equals and hashCode functions to be consistent with each other.

like image 155
Sergey Kalinichenko Avatar answered Sep 30 '22 13:09

Sergey Kalinichenko