Java Reference
In-Depth Information
The only requirement for a hashCode() method is that if the m.equals(n) method returns true , m.hashCode()
must return the same value as n.hashCode() . Because your equals() method uses (x, y) coordinates to test for
equality, you return the sum of x and y coordinates from the hashCode() method, which fulfills the technical
requirement. Practically, you need to use a better hashing algorithm to compute the hash value.
You have written a few lines of codes in the equals() method of the SmartPoint class. Let's go through the logic
one by one. First, you need to check if the object passed is the same as the object on which the method is called. If two
objects are the same, you consider them equal by retuning true . This is accomplished by the following code:
// Are they the same?
if (this == otherObject) {
return true;
}
If the parameter being passed is null , the two objects cannot be the same. Note that the object on which the
method is called can never be null because you cannot call a method on a null reference. Java runtime will throw
runtime exception when an attempt is made to call a method on a null reference. The following code makes sure that
you are comparing two non-null objects:
// Is otherObject a null reference?
if (otherObject == null) {
return false;
}
The parameter type of the method is Object . This means that any type of object reference can be passed. For
example, you can use apple.equals(orange) , where apple and orange are references to an Apple object and an
Orange object, respectively. In your case, you want to compare only a SmartPoint object to another SmartPoint
object. To make sure that the objects being compared are of the same class, you need the following code. If someone
calls the method with a parameter that is not a SmartPoint object, it returns false .
// Do they have the same class?
if (this.getClass() != otherObject.getClass()) {
return false;
}
At this point, you are sure that someone is trying to compare two non-null SmartPoint objects that have different
identity (references). Now you would like to compare the (x, y) coordinates of two objects. To access the x and y
instance variables of the otherObject formal parameter, you must cast it to a SmartPoint object. The following
statement does it:
// Get the reference of otherObject in a SmartPoint variable
SmartPoint otherPoint = (SmartPoint)otherObject;
At this point, it is just the matter of comparing the values of x and y instance variables of the two SmartPoint
objects. If they are the same, you consider two objects equal by returning true . Otherwise, two objects are not equal
and you return false . This is accomplished by the following code:
// Do they have the same x and y co-ordinates
boolean isSamePoint = (this.x == otherPoint.x && this.y == otherPoint.y);
return isSamePoint;
 
Search WWH ::




Custom Search