I'm a computer engineering student and I've started Java
one week ago. I've been studying these days generic types and I wanted to mix it with equals and Overriding, so I wrote a program that creates an object called "Punto" with two attributes (pointX, pointY) so it simulates coordinates. I wrote a static method outside the main class that uses two "Puntos" as parameters and equals them. Here's the code of that method:
public static boolean iguales(PuntoImpl<Double> p1, PuntoImpl<Double> p2){
return p1.equals(p2);
}
And here's my try of overriding equals:
@Override
public boolean equals(final Object obj)
{
if (obj == null || !(obj instanceof PuntoImpl))
return false;
PuntoImpl<T> other = (PuntoImpl<T>) obj;
if (other.puntoX != this.puntoX) return false;
if (other.puntoY != this.puntoY) return false;
return true;
}
I'm trying to equals two points with same parameters in coordinate X and coordinate Y, but it returns me false. Can you help me to find the error?
You're comparing Double
values by reference equality. I suspect you want if (!other.puntoX.equals(this.puntoX))
etc. I'd actually write this code as:
@Override
public boolean equals(final Object obj)
{
if (obj == null || obj.getClass() != getClass()) {
return false;
}
if (obj == this) {
return true;
}
PuntoImpl<T> other = (PuntoImpl<T>) obj;
return other.puntoX.equals(this.puntoX) &&
other.puntoY.equals(this.puntoY);
}
Don't forget to override hashCode
as well.
Also note that comparing floating point values for exact equality can often give unexpected results. Instead of overriding equals
, you may want to provide a way of finding the distance between points, so you can compare them with a certain tolerance.
See more on this question at Stackoverflow