I am trying to implement the following example to override the equality and hashCode method if the class has reference type member but no luck. Any help would be highly appreciated. Thanking you all in advance..
class Point{
private int x, y;
Point (int x, int y)
{
this.x =x;
this.y = y;
}
}
class Circle
{
int radius;
Point point ;
Circle(int x, int y, int radius)
{
point = new Point (x ,y);
this.radius = radius;
}
@Override
public boolean equals(Object arg) {
if(arg == null) return false;
if(arg == this) return true;
if(arg instanceof Circle)
{
if(this.point ==((Circle) arg).point && this.radius == ((Circle) arg).radius)
{
return true;
}
}
return false;
}
@Override
public int hashCode() {
return point.hashCode() ^ this.radius;
}
}
public class TestClass{
public static void main(String args[])
{
Set<Circle> circle = new HashSet<> ();
circle.add(new Circle(10,20,40));
System.out.println(circle.contains(new Circle(10,20,40))); //
}
}
**************************Edited Version, suggested by Alnitak*****************
Now i do get the expected result "true" for equal and "false" for non-equal objects. But the print statement in the Circle's equal method is not executed when the objects values are not equal. I don't know what i am missing, though i get the equality result "false" as expected for non equal objects.
class Point{
private int x, y;
Point (int x, int y)
{
this.x =x;
this.y = y;
}
@Override
public boolean equals(Object arg) {
if(arg == null ) return false;
if(arg== this) return true;
if(arg instanceof Point)
{
Point p = (Point) arg;
if(p.x == x && p.y == y )
{
return true;
}
}
return false;
}
@Override
public int hashCode() {
return (this.x*1124739) ^ (this.y*95);
}
}
class Circle
{
int radius;
Point point ;
Circle(int x, int y, int radius)
{
System.out.println("Circle object created x= " + x);
point = new Point (x ,y);
this.radius = radius;
}
@Override
public boolean equals(Object arg) {
if(arg == null) return false;
if(arg == this) return true;
if(arg instanceof Circle)
{
System.out.println("checking circles objects for equality ");
// Doesn't get printed when circle objects values are not equal
Circle c = (Circle) arg;
return (point.equals(c.point) && radius == c.radius);
}
return false;
}
@Override
public int hashCode() {
return point.hashCode() ^ this.radius *37;
}
}
public class TestClass{
public static void main(String args[])
{
Set<Circle> circle = new HashSet<> ();
circle.add(new Circle(10,20,40));
System.out.println(circle.contains(new Circle(11,20,40))); //
}
}