Docsity

Java Object Equality and Hashcode: Best Practices, Lecture notes of Art

Toggle sidebar
bg1
25
CHAPTER 3
Methods Common to All Objects
ALTHOUGH Object is a concrete class, it is designed primarily for extension. All
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:
‱Each instance of the class is inherently unique. This is true for classes that
represent active entities rather than values, such as Thread. The equals imple-
mentation provided by Object has exactly the right behavior for these classes.
‱You don’t care whether the class provides a “logical equality” test. For
example, java.util.R andom could have overridden equals to check whether
two Random instances would produce the same sequence of random numbers
going forward, but the designers didn’t think that clients would need or want
this functionality. Under these circumstances, the equals implementation
inherited from Object is adequate.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22

Partial preview of the text

Download Java Object Equality and Hashcode: Best Practices and more Lecture notes Art in PDF only on Docsity!

C H A P T E R 3

Methods Common to All Objects

A LTHOUGH Object is a concrete class, it is designed primarily for extension. All

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:

  • Each instance of the class is inherently unique. This is true for classes that represent active entities rather than values, such as Thread. The equals imple- mentation provided by Object has exactly the right behavior for these classes.
  • You don’t care whether the class provides a “logical equality” test. For example, java.util.Random could have overridden equals to check whether two Random instances would produce the same sequence of random numbers going forward, but the designers didn’t think that clients would need or want this functionality. Under these circumstances, the equals implementation inherited from Object is adequate.

26 CHAPTER 3^ METHODS COMMON TO ALL OBJECTS

  • A superclass has already overridden equals, and the behavior inherited from the superclass is appropriate for this class. For example, most Set implementations inherit their equals implementation from AbstractSet, List implementations from AbstractList, and Map implementations from AbstractMap.
  • The class is private or package-private, and you are certain that its equals method will never be invoked. Arguably, the equals method should be over- ridden under these circumstances, in case it is accidentally invoked someday:

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.

28 CHAPTER 3^ METHODS COMMON TO ALL OBJECTS

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

ITEM 7: OBEY THE GENERAL CONTRACT WHEN OVERRIDING EQUALS 29

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; }

ITEM 7: OBEY THE GENERAL CONTRACT WHEN OVERRIDING EQUALS 31

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; }

/**

  • Returns the point-view of this color point. */ public Point asPoint() { return point; }

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

32 CHAPTER 3^ METHODS COMMON TO ALL OBJECTS

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:

34 CHAPTER 3^ METHODS COMMON TO ALL OBJECTS

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.

  1. When you are finished writing your equals method, ask yourself three questions: Is it symmetric, is it transitive, and is it consistent? (The other two properties generally take care of themselves.) If not, figure out why these properties fail to hold, and modify the method accordingly.

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:

  • Always override hashCode when you override equals (Item 8).
  • Don’t try to be too clever. If you simply test fields for equality, it’s not hard to adhere to the equals contract. If you are overly aggressive in searching for equivalence, it’s easy to get into trouble. It is generally a bad idea to take any form of aliasing into account. For example, the File class shouldn’t attempt to equate symbolic links referring to the same file. Thankfully, it doesn’t.
  • Don’t write an equals method that relies on unreliable resources. It’s ex- tremely difficult to satisfy the consistency requirement if you do this. For ex- ample, java.net.URL’s equals method relies on the IP addresses of the hosts in URLs being compared. Translating a host name to an IP address can require network access, and it isn’t guaranteed to yield the same results over time. This can cause the URL equals method to violate the equals contract, and it has caused problems in practice. (Unfortunately, this behavior cannot be changed due to compatibility requirements.) With few exceptions, equals methods should perform deterministic computations on memory-resident objects.

ITEM 7: OBEY THE GENERAL CONTRACT WHEN OVERRIDING EQUALS 35

  • Don’t substitute another type for Object in the equals declaration. It is not

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).

ITEM 8: ALWAYS OVERRIDE HASHCODE WHEN YOU OVERRIDE EQUALS 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.

38 CHAPTER 3^ METHODS COMMON TO ALL OBJECTS

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:

  1. Store some constant nonzero value, say 17, in an int variable called result.
  2. For each significant field f in your object (each field taken into account by the equals method, that is), do the following:

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).

40 CHAPTER 3^ METHODS COMMON TO ALL OBJECTS

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

ITEM 8: ALWAYS OVERRIDE HASHCODE WHEN YOU OVERRIDE EQUALS 41

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.

ITEM 9: ALWAYS OVERRIDE TOSTRING 43

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:

  • Returns the string representation of this phone number.
  • The string consists of fourteen characters whose format
  • is "(XXX) YYY-ZZZZ", where XXX is the area code, YYY is
  • the extension, and ZZZZ is the exchange. (Each of the
  • capital letters represents a single decimal digit.)
  • If any of the three parts of this phone number is too small
  • to fill up its field, the field is padded with leading zeros.
  • For example, if the value of the exchange is 123, the last
  • four characters of the string representation will be "0123".
  • Note that there is a single space separating the closing
  • parenthesis after the area code from the first digit of the
  • exchange. */ public String toString() { return "(" + toPaddedString(areaCode, 3) + ") " + toPaddedString(exchange, 3) + "-" + toPaddedString(extension, 4); }

private static String[] ZEROS = {"", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000"};

44 CHAPTER 3^ METHODS COMMON TO ALL OBJECTS

  • Translates an int to a string of the specified length,
  • padded with leading zeros. Assumes i >= 0,
  • 1 <= length <= 10, and Integer.toString(i) <= length. */ private static String toPaddedString(int i, int length) { String s = Integer.toString(i); return ZEROS[length - s.length()] + s; }

If you decide not to specify a format, the documentation comment should read something like this:

  • Returns a brief description of this potion. The exact details
  • of the representation are unspecified and subject to change,
  • but the following may be regarded as typical:
  • "[Potion #9: type=love, smell=turpentine, look=india ink]" */ public String toString() { ... }

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.