haloid2010 haloid2010 - 10 days ago 5
Java Question

Basic java equals() override help needed

I am currently working on a simple line program in java. There will be no actual GUI, so it is completely text based.

We are required to have a point class and a line class that includes to point objects.

The problem I encountered was involving the equals method for my point class. Considering each point only has two POSITIVE int values, an x and a y, and I'm having issues here, I'm worried I will have problems when I have to compare lines, which will involve comparing the points, the int width and the string color.

This is what the code for my equals method for my point class looks.

@Override
public boolean equals(Point that) {
if(this==that)
return true;
//if
if(this.x==that.getX() && this.y==that.getY())
return true;
return false;
}


Any and all help would be appreciated.

Answer

The signature needs to contain Object, not Point. You then need the obvious checks to make sure the object is in fact a point and it's non-null.

Apart from that, as you've put it there I don't see any problem with the method, it's reflexive, symmetric, consistent and transitive as far as I can make out. If your class used doubles then I'd say put a delta value in when comparing them - but obviously with ints that's not a problem.

The indirect problem though is that you really should override hashcode as well to behave in the same way, otherwise you could run into strange issues when adding your points to collections that make use of hashcode() (by contract they're expected to compare the objects in the same way.)

Comments