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?