0

I want to override the equals and hashCode method in my Point class. I want to use the Point1 class object in my list and I want to check if on list there is a point with the same coordinates and it needn't to be the same object. only have the same values in fields.

here is my code and I have no idea why it doesn't work

package prac1; import java.util.ArrayList; import java.util.List; class Point{ private Integer x; private Integer y; Point(int x,int y) { this.x = x; this.y = y; } @Override public int hashCode() { int hash = 5; hash = hash +(this.x != null ? this.x.hashCode() : 0); hash = hash/12 + (this.y != null ? this.y.hashCode() : 0); //to have unique hashCode for different objects return hash; } @Override public boolean equals(Object other) { if(this == other) return true; if(other == null) return false; if(getClass() != other.getClass()) return false; Point1 test = (Point1)other; if(this.x == test.getX() && this.y == test.getY()) return true; return false; } int getX(){ return this.x; } int getY() {return this.y; } } public class NewClass{ public static void main(String args[]) { List<Point1> lista = new ArrayList<Point1>(); Point1 t = new Point1(1,1); lista.add(t); System.out.println(lista.contains(t)); // true System.out.println(lista.contains(new Point1(1,1))); // false ? } } 

it returns:

 true false 

Can anyone tell me what am I doing wrong?

1
  • what is Point1 ? is that supposed to be Point? also: important to notice: when I run your code, assuming that Point and Point1 are supposed to be the same class, I get 'true' 'true' as result Commented May 29, 2014 at 9:55

1 Answer 1

3

If I rename your Point class to Point1 then it produces true true on my machine, so your code works.

There is a bug in your code however. You are using == on Integer objects. This will only work with integer values between -128 and 127 (reference) because these are cached by the JVM. But it won't work for larger/smaller values. Instead use .equals

Point1 test = (Point1)other; if(this.x.equals(test.getX()) && this.y.equals(test.getY())) return true; return false; 

Here I left out an if for when this.x == null or this.y == null which is impossible in your code at the moment since the constructor accepts primitives only.

Sign up to request clarification or add additional context in comments.

1 Comment

@user3131037 You're welcome. Can I ask why you are using integer division in your hash function? This seems like it might cause you to lose set bits and cause more hash collisions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.