


























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



























of its nonfinal methods (equals, hashCode, toString, clone, and finalize) have
explicit general contracts because they are designed to be overridden. It is the
responsibility of any class overriding these methods to obey their general con-
tracts; failure to do so will prevent other classes that depend on these contracts
from functioning properly in conjunction with the class.
This chapter tells you when and how to override the nonfinal Object methods.
The finalize method is omitted from this chapter because it was discussed in
Item 6. While not an Object method, Comparable.compareTo is discussed in this
chapter because it has a similar character.
Item 7: Obey the general contract when overriding equals
Overriding the equals method seems simple, but there are many ways to get it
wrong, and the consequences can be dire. The easiest way to avoid problems is not
to override the equals method, in which case each instance is equal only to itself.
This is the right thing to do if any of the following conditions apply:
public boolean equals(Object o) { throw new UnsupportedOperationException(); }
So when is it appropriate to override Object.equals? When a class has a notion of logical equality that differs from mere object identity, and a superclass has not already overridden equals to implement the desired behavior. This is gen- erally the case for value classes , such as Integer or Date. A programmer who compares references to value objects using the equals method expects to find out whether they are logically equivalent, not whether they refer to the same object. Not only is overriding the equals method necessary to satisfy programmer expec- tations, it enables instances of the class to serve as map keys or set elements with predictable, desirable behavior. One kind of value class that does not require the equals method to be overrid- den is the typesafe enum (Item 21). Because typesafe enum classes guarantee that at most one object exists with each value, Objectâs equals method is equivalent to a logical equals method for such classes. When you override the equals method, you must adhere to its general con- tract. Here is the contract, copied from the specification for java.lang.Object:
The equals method implements an equivalence relation : n (^) It is reflexive : For any reference value x, x.equals(x) must return true.
n (^) It is symmetric : For any reference values x and y, x.equals(y) must return true if and only if y.equals(x) returns true. n (^) It is transitive : For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true. n (^) It is consistent : For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified. n (^) For any non-null reference value x, x.equals(null) must return false.
The well-intentioned equals method in this class naively attempts to interop- erate with ordinary strings. Letâs suppose that we have one case-sensitive string and one ordinary one:
CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); String s = "polish";
As expected, cis.equals(s) returns true. The problem is that while the equals method in CaseInsensitiveString knows about ordinary strings, the equals method in String is oblivious to case-insensitive strings. Therefore s.equals(cis) returns false, a clear violation of symmetry. Suppose you put a case-insensitive string into a collection:
List list = new ArrayList(); list.add(cis);
What does list.contains(s) return at this point? Who knows? In Sunâs cur- rent implementation, it happens to return false, but thatâs just an implementation artifact. In another implementation, it could just as easily return true or throw a run-time exception. Once youâve violated the equals contract, you simply donât know how other objects will behave when confronted with your object. To eliminate the problem, merely remove the ill-conceived attempt to interop- erate with String from the equals method. Once you do this, you can refactor the method to give it a single return:
public boolean equals(Object o) { return o instanceof CaseInsensitiveString && ((CaseInsensitiveString)o).s.equalsIgnoreCase(s); }
Transitivity âThe third requirement of the equals contract says that if one object is equal to a second and the second object is equal to a third, then the first object must be equal to the third. Again, itâs not hard to imagine violating this requirement unintentionally. Consider the case of a programmer who creates a subclass that adds a new aspect to its superclass. In other words, the subclass adds
a piece of information that affects equals comparisons. Letâs start with a simple
immutable two-dimensional point class:
public class Point { private final int x; private final int y; public Point(int x, int y) { this.x = x; this.y = y; }
public boolean equals(Object o) { if (!(o instanceof Point)) return false; Point p = (Point)o; return p.x == x && p.y == y; }
... // Remainder omitted }
Suppose you want to extend this class, adding the notion of color to a point:
public class ColorPoint extends Point { private Color color;
public ColorPoint(int x, int y, Color color) { super(x, y); this.color = color; }
... // Remainder omitted }
How should the equals method look? If you leave it out entirely, the imple-
mentation is inherited from Point, and color information is ignored in equals
comparisons. While this does not violate the equals contract, it is clearly unac-
ceptable. Suppose you write an equals method that returns true only if its argu-
ment is another color point with the same position and color:
// Broken - violates symmetry! public boolean equals(Object o) { if (!(o instanceof ColorPoint)) return false; ColorPoint cp = (ColorPoint)o; return super.equals(o) && cp.color == color; }
Point, give ColorPoint a private Point field and a public view method (Item 4)
that returns the point at the same position as this color point:
// Adds an aspect without violating the equals contract public class ColorPoint { private Point point; private Color color;
public ColorPoint(int x, int y, Color color) { point = new Point(x, y); this.color = color; }
/**
public boolean equals(Object o) { if (!(o instanceof ColorPoint)) return false; ColorPoint cp = (ColorPoint)o; return cp.point.equals(point) && cp.color.equals(color); }
... // Remainder omitted }
There are some classes in the Java platform libraries that subclass an instantia-
ble class and add an aspect. For example, java.sql.Timestamp subclasses
java.util.Date adding a nanoseconds field. The equals implementation for
Timestamp does violate symmetry and can cause erratic behavior if Timestamp
and Date objects are used in the same collection or are otherwise intermixed. The
Timestamp class has a disclaimer cautioning the programmer against mixing dates
and timestamps. While you wonât get into trouble as long as you donât mix them,
thereâs nothing preventing you from doing so, and the resulting errors could be
hard to debug. The TimeStamp class is an anomaly and should not be emulated.
Note that you can add an aspect to a subclass of an abstract class without vio-
lating the equals contract. This is important for the sort of class hierarchies that
you get by following the advice in Item 20, âReplace unions with class hierar-
chies.â For example, you could have an abstract Shape class with no aspects, a
Circle subclass that adds a radius field, and a Rectangle subclass that adds
length and width fields. Problems of the sort just shown will not occur as long as it is impossible to create an instance of the superclass. Consistency âThe fourth requirement of the equals contract says that if two objects are equal, they must remain equal for all time, unless one (or both) of them is modified. This isnât so much a true requirement as a reminder that mutable objects can be equal to different objects at different times while immutable objects canât. When you write a class, think hard about whether it should be immutable (Item 13). If you conclude that it should, make sure that your equals method enforces the restriction that equal objects remain equal and unequal objects remain unequal for all time. âNon-nullityââ The final requirement, which in the absence of a name I have taken the liberty of calling ânon-nullity,â says that all objects must be unequal to null. While it is hard to imagine accidentally returning true in response to the invocation o.equals(null), it isnât hard to imagine accidentally throwing a NullPointerException. The general contract does not allow this. Many classes have equals methods that guard against it with an explicit test for null:
public boolean equals(Object o) { if (o == null) return false; ... }
This test is not necessary. To test its argument for equality, the equals method must first cast the argument to an appropriate type so its accessors may be invoked or its fields accessed. Before doing the cast, the method must use the instanceof operator to check that its argument is of the correct type:
public boolean equals(Object o) { if (!(o instanceof MyType)) return false; ... }
If this type check were missing and the equals method were passed an argument of the wrong type, the equals method would throw a ClassCastException, which violates the equals contract. But the instanceof operator is specified to return false if its first operand is null, regardless of what type appears in the second operand [JLS, 15.19.2]. Therefore the type check will return false if null is passed in, so you donât need a separate null check. Putting it all together, hereâs a recipe for a high-quality equals method:
a canonical form in each object, so that the equals method can do cheap exact comparisons on these canonical forms rather than more costly inexact compar- isons. This technique is most appropriate for immutable classes (Item 13), as the canonical form would have to be kept up to date if the object could change.
The performance of the equals method may be affected by the order in which fields are compared. For best performance, you should first compare fields that are more likely to differ, less expensive to compare, or, ideally, both. You must not compare fields that are not part of an objectâs logical state, such as Object fields used to synchronize operations. You need not compare redundant fields , which can be calculated from âsignificant fields,â but doing so may improve the performance of the equals method. If a redundant field amounts to a sum- mary description of the entire object, comparing this field will save you the ex- pense of comparing the actual data if the comparison fails.
For a concrete example of an equals method constructed according to the above recipe, see PhoneNumber.equals in Item 8. Here are a few final caveats:
uncommon for a programmer to write an equals method that looks like the fol- lowing, and then spend hours puzzling over why it doesnât work properly:
public boolean equals(MyClass o) { ... }
The problem is that this method does not override Object.equals, whose ar- gument is of type Object, but overloads it instead (Item 26). It is acceptable to provide such a âstrongly typedâ equals method in addition to the normal one as long as the two methods return the same result but there is no compelling reason to do so. It may provide minor performance gains under certain circum- stances, but it isnât worth the added complexity (Item 37).
this.areaCode = (short) areaCode; this.exchange = (short) exchange; this.extension = (short) extension; }
private static void rangeCheck(int arg, int max, String name) { if (arg < 0 || arg > max) throw new IllegalArgumentException(name +": " + arg); }
public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof PhoneNumber)) return false; PhoneNumber pn = (PhoneNumber)o; return pn.extension == extension && pn.exchange == exchange && pn.areaCode == areaCode; }
// No hashCode method!
... // Remainder omitted }
Suppose you attempt to use this class with a HashMap:
Map m = new HashMap(); m.put(new PhoneNumber(408, 867, 5309), "Jenny");
At this point, you might expect m.get(new PhoneNumber(408, 867 , 5309)) to
return "Jenny", but it returns null. Notice that two PhoneNumber instances are
involved: One is used for insertion into the HashMap, and a second, equal, instance
is used for (attempted) retrieval. The PhoneNumber classâs failure to override
hashCode causes the two equal instances to have unequal hash codes, in violation
of the hashCode contract. Therefore the get method looks for the phone number
in a different hash bucket from the one in which it was stored by the put method.
Fixing this problem is as simple as providing a proper hashCode method for the
PhoneNumber class.
So what should a hashCode method look like? Itâs trivial to write one that is legal but not good. This one, for example, is always legal, but it should never be used:
// The worst possible legal hash function - never use! public int hashCode() { return 42; }
Itâs legal because it ensures that equal objects have the same hash code. Itâs atrocious because it ensures that every object has the same hash code. Therefore every object hashes to the same bucket, and hash tables degenerate to linked lists. Programs that should run in linear time run instead in quadratic time. For large hash tables, this is the difference between working and not working. A good hash function tends to produce unequal hash codes for unequal objects. This is exactly what is meant by the third provision of the hashCode con- tract. Ideally, a hash function should distribute any reasonable collection of unequal instances uniformly across all possible hash values. Achieving this ideal can be extremely difficult. Luckily it is not too difficult to achieve a fair approxi- mation. Here is a simple recipe:
a. Compute an int hash code c for the field: i. If the field is a boolean, compute (f? 0 : 1).
ii. If the field is a byte, char, short, or int, compute (int)f.
iii. If the field is a long, compute (int)(f ^ (f >>> 32)).
iv. If the field is a float compute Float.floatToIntBits(f).
v. If the field is a double, compute Double.doubleToLongBits(f), and then hash the resulting long as in step 2.a.iii.
vi. If the field is an object reference and this classâs equals method compares the field by recursively invoking equals, recursively invoke hashCode on the field. If a more complex comparison is required, compute a âcanonical representationâ for this field and invoke hashCode on the canonical representation. If the value of the field is null, return 0 (or some other constant, but 0 is traditional).
Because this method returns the result of a simple deterministic computation whose only inputs are the three significant fields in a PhoneNumber instance, it should be clear that equal PhoneNumber instances have equal hash codes. This method is, in fact, a perfectly reasonable hashCode implementation for Phone- Number, on a par with those in the Java platform libraries as of release 1.4. It is simple, is reasonably fast, and does a reasonable job of dispersing unequal phone numbers into different hash buckets. If a class is immutable and the cost of computing the hash code is significant, you might consider caching the hash code in the object rather than recalculating it each time it is requested. If you believe that most objects of this type will be used as hash keys, then you should calculate the hash code when the instance is created. Otherwise, you might choose to lazily initialize it the first time hashCode is invoked (Item 48). It is not clear that our PhoneNumber class merits this treatment, but just to show you how itâs done:
// Lazily initialized, cached hashCode private volatile int hashCode = 0; // (See Item 48)
public int hashCode() { if (hashCode == 0) { int result = 17; result = 37result + areaCode; result = 37result + exchange; result = 37*result + extension; hashCode = result; } return hashCode; }
While the recipe in this item yields reasonably good hash functions, it does not yield state-of-the-art hash functions, nor do the Java platform libraries provide such hash functions as of release 1.4. Writing such hash functions is a topic of active research and an activity best left to mathematicians and theoretical com- puter scientists. Perhaps a later release of the Java platform will provide state-of- the-art hash functions for its classes and utility methods to allow average program- mers to construct such hash functions. In the meantime, the techniques described in this item should be adequate for most applications. Do not be tempted to exclude significant parts of an object from the hash code computation to improve performance. While the resulting hash function may run faster, its quality may degrade to the point where hash tables become unusably slow. In particular, the hash function may, in practice, be confronted
with a large collection of instances that differ largely in the regions that youâve
chosen to ignore. If this happens, the hash function will map all of the instances to
a very few hash codes, and hash-based collections will display quadratic perfor-
mance. This is not just a theoretical problem. The String hash function imple-
mented in all Java platform releases prior to release 1.2 examined at most sixteen
characters, evenly spaced throughout the string, starting with the first character.
For large collections of hierarchical names such as URLs, this hash function dis-
played exactly the pathological behavior noted here.
Many classes in the Java platform libraries, such as String, Integer, and
Date, specify the exact value returned by their hashCode method as a function of
the instance value. This is generally not a good idea, as it severely limits your abil-
ity to improve the hash function in future releases. If you leave the details of a
hash function unspecified and a flaw is found in it, you can fix the hash function in
the next release without fear of breaking compatibility with clients who depend on
the exact values returned by the hash function.
unambiguous, human-readable representation of the object. This representation
can be used for input and output and in persistent human-readable data objects
such as XML documents. If you specify the format, itâs usually a good idea to pro-
vide a matching String constructor (or static factory, see Item 1), so programmers
can easily translate back and forth between the object and its string representation.
This approach is taken by many value classes in the Java platform libraries,
including BigInteger, BigDecimal, and most of the primitive wrapper classes.
The disadvantage of specifying the format of the toString return value is that
once youâve specified it, youâre stuck with it for life, assuming your class is
widely used. Programmers will write code to parse the representation, to generate
it, and to embed it into persistent data. If you change the representation in a future
release, youâll break their code and data, and they will yowl. By failing to specify
a format, you preserve the flexibility to add information or improve the format in a
subsequent release.
Whether or not you decide to specify the format, you should clearly docu-
ment your intentions. If you specify the format, you should do so precisely. For
example, hereâs a toString method to go with the PhoneNumber class in Item 8:
private static String[] ZEROS = {"", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000"};
If you decide not to specify a format, the documentation comment should read something like this:
After reading this comment, programmers who produce code or persistent data that depend on the details of the format will have no one but themselves to blame when the format is changed. Whether or not you specify the format, it is always a good idea to provide programmatic access to all of the information contained in the value returned by toString. For example, the PhoneNumber class should contain accessors for the area code, exchange, and extension. If you fail to do this, you force program- mers who need this information to parse the string. Besides reducing performance and making unnecessary work for programmers, this process is error prone and results in fragile systems that break if you change the format. By failing to provide accessors, you turn the string format into a de facto API, even if youâve specified that itâs subject to change.