Java Reference
In-Depth Information
In that last return statement, we can safely use the String.equals method to compare the contents
of the two UPC fields. We could not use it earlier, as we did not know if the local UPC field contained
null (in which case the last return statement would have generated a NullPointerException );
likewise, we did not know if the other UPC value contained null , so we could not reverse the logic
( otherDVD.getUPC().equals(upc) ) as it may also have thrown a NullPointerException . It is only
after we have validated that at least one of the two UPC values is not null that we can use the equals
method.
If the UPC did not uniquely identify the DVD, we might consider having more complex
logic; for example, we might compare the UPC, the title, and the main actor (it is unlikely that
an actor would work in a film with the same title as one they had previously worked in, and
that had the same UPC). However, we would probably not check the number of DVDs avail-
able, as they are not unique to the DVD.
It is strongly recommended that whenever you override the equals method, you should
also override the hashCode method, as the two are often used together. Once again, we have
used the fact that the UPC number uniquely identifies the DVD, and simply reused the UPC's
hash code as the DVD's hash code:
462 public int hashCode() {
463 return upc.hashCode();
464 }
465 }
It is important to try to return different hash codes for instances of a class that are not
considered equal where possible, while at the same time the same hash code value must be
returned for instances of a class that are considered equal no matter how many times it is run
on a single JVM (unless some of its internal field data is changed in such a way that it is no
longer considered equal to the old instance). If we had added extra checking to our equals
method (such as checking the actor's name), then we might want to consider modifying our
hash code generator to take into account the extra uniqueness checking. For example, we
might choose to add the hash codes for both the UPC and the actor's name, and return the
sum as the new hash code.
Tip A unique hash code per unique instance of a class may not be possible. Furthermore, even if you
spent considerable time developing an algorithm to generate a hash code that is highly likely to be unique,
there would almost certainly be a loss of efficiency caused by the extra time required to execute the algo-
rithm. If you need to generate your own hashCode methods, we recommend that you don't spend too much
time in this method unless code profiling shows that a significant amount of time is being spent in methods
that rely on the hash code (such as the HashMap.get method).
Search WWH ::




Custom Search