Sub topic 10
Floating-point, array, and nullable fields
This chapter assumes you can already write a basic equals and hashCode pair for a class with int and String fields. It covers three kinds of field where the obvious code fails: double and float values, arrays, and references that may be null. Each has its own rule for comparing and hashing.
Why the obvious code fails
For int and other integral fields, == and Integer.hashCode do what you expect. Three other kinds of field do not:
- A
doublecan holdNaNand negative zero, and==treats both in surprising ways. - An array inherits
equalsandhashCodefromObject, so it compares by identity. - A reference that is
nullthrowsNullPointerExceptionthe moment you call a method on it.
The sections below take them in turn, then combine them in one class.
Floating-point fields
Comparing a double field with == breaks the equals contract in two ways. NaN == NaN is false, so an object containing NaN would not equal itself, which breaks reflexivity. And 0.0 == -0.0 is true, even though the two values are distinguishable (for example, 1.0 / 0.0 and 1.0 / -0.0 give different infinities).
The wrapper classes define a stricter notion of equality. Double.compare(a, b) returns 0 only when the two values are the same by that notion. Double.hashCode(d) is consistent with it.
public class DoubleDemo {
public static void main(String[] args) {
double nan = Double.NaN;
System.out.println(nan == nan); // false
System.out.println(Double.valueOf(nan).equals(nan)); // true
System.out.println(Double.compare(nan, nan)); // 0
System.out.println(0.0 == -0.0); // true
System.out.println(Double.valueOf(0.0).equals(-0.0)); // false
System.out.println(Double.compare(0.0, -0.0)); // 1
}
}Double.compare(a, b) == 0 is the right test for a double field in equals. Use Float.compare for float fields. Both methods treat every NaN bit pattern as the same value, and both order -0.0 before 0.0.
For hashing, call Double.hashCode(score) or Float.hashCode(score). If you pass the field to Objects.hash, it is boxed to a Double and Double.hashCode is used anyway.
Two values with Double.compare(a, b) == 0 always have the same Double.hashCode. That is exactly the consistency the hashCode contract requires.
Exact equality is still a design decision
Double.compare tests exact equality. 0.1 + 0.2 and 0.3 are different doubles, so they are unequal. If your class wants "equal within a tolerance", do not put that in equals. A tolerance check is not transitive: a can be close to b, and b close to c, while a is not close to c. It also cannot be paired with a matching hashCode. Keep equals exact and write a separate method such as isCloseTo(other, epsilon).
BigDecimal has a similar trap
BigDecimal.equals compares the scale as well as the value, so new BigDecimal("2.0") and new BigDecimal("2.00") are not equal. compareTo returns 0 for them. If the scale is not meaningful in your class, compare with compareTo(...) == 0 and hash stripTrailingZeros(). Otherwise, use equals and hashCode on the BigDecimal and accept that scale is part of the value.
Array fields
An array's equals and hashCode are the ones from Object. They test identity.
import java.util.Arrays;
import java.util.Objects;
public class ArrayDemo {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b); // false
System.out.println(a.equals(b)); // false: identity
System.out.println(Arrays.equals(a, b)); // true: element by element
System.out.println(Arrays.hashCode(a) == Arrays.hashCode(b)); // true
System.out.println(a.hashCode() == b.hashCode()); // almost always false
int[][] grid1 = {{1}, {2}};
int[][] grid2 = {{1}, {2}};
System.out.println(Arrays.equals(grid1, grid2)); // false: inner arrays compared by identity
System.out.println(Arrays.deepEquals(grid1, grid2)); // true
}
}Choose the helper by what the array holds:
Arrays.equalsandArrays.hashCodefor one-dimensional arrays. They compare elements with==for primitives and withequalsfor objects.Arrays.deepEqualsandArrays.deepHashCodewhen elements can themselves be arrays.
The double[] and float[] overloads use the same bit-based comparison as Double.compare. A double[] holding NaN therefore equals itself, as you would want.
The Objects.hash trap with arrays
Objects.hash takes varargs of type Object.... If you pass a single int[], the compiler wraps it as a one-element Object[]. The hash then uses the array's identity hash code. This code compiles and looks correct, but it breaks the contract:
int[] values = {1, 2, 3};
int bad = Objects.hash(values); // hashes the array reference
int good = Arrays.hashCode(values); // hashes the contentsA reference to an Object[] is spread into the varargs instead, which is a second, different surprise. Hash array fields explicitly with Arrays.hashCode, as the full example below does.
Defensive copies
An array field is mutable even when the field is final. If the caller keeps a reference to the array passed to the constructor, they can change the contents later, which changes equals and hashCode for an object that was supposed to be immutable. Copy the array on the way in with clone(). Copy it on the way out too, if you expose it through an accessor.
Nullable fields
label.equals(other.label) throws when label is null. Two helpers cover this:
Objects.equals(a, b)returnstrueif both arenull,falseif only one is, and otherwisea.equals(b).Objects.hashCode(o)returns0fornullando.hashCode()otherwise.
Objects.hash(...) applies Objects.hashCode to each argument, so null arguments are safe. Arrays.equals and Arrays.hashCode also accept null arrays, and a null array hashes to 0.
import java.util.Arrays;
import java.util.Objects;
public class NullDemo {
public static void main(String[] args) {
System.out.println(Objects.equals(null, null)); // true
System.out.println(Objects.equals(null, "x")); // false
System.out.println(Objects.hashCode(null)); // 0
System.out.println(Arrays.equals((int[]) null, (int[]) null)); // true
System.out.println(Arrays.hashCode((int[]) null)); // 0
}
}Note that the helpers treat null and "empty" as different. Arrays.hashCode(new int[0]) is 1, and Arrays.hashCode((int[]) null) is 0. The values are different, which is fine, because null and an empty array are not equal either.
Choosing the right comparison
| Field type | Test in `equals` | Contribution to `hashCode` |
|---|---|---|
| `int`, `long`, `short`, `byte`, `char` | `==` | `Integer.hashCode`, `Long.hashCode`, and so on |
| `boolean` | `==` | `Boolean.hashCode` |
| `double` | `Double.compare(a, b) == 0` | `Double.hashCode` |
| `float` | `Float.compare(a, b) == 0` | `Float.hashCode` |
| Object reference that may be `null` | `Objects.equals` | `Objects.hashCode` |
| Array of primitives or flat object array | `Arrays.equals` | `Arrays.hashCode` |
| Array that may contain arrays | `Arrays.deepEquals` | `Arrays.deepHashCode` |
Putting it together
Sample has a nullable String, a double, and an int[]. Each field uses the matching helper.
import java.util.Arrays;
import java.util.Objects;
public final class Sample {
private final String label; // may be null
private final double score;
private final int[] values;
public Sample(String label, double score, int[] values) {
this.label = label;
this.score = score;
this.values = values.clone(); // defensive copy; throws if values is null
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Sample)) return false;
Sample s = (Sample) o;
return Double.compare(score, s.score) == 0
&& Objects.equals(label, s.label)
&& Arrays.equals(values, s.values);
}
@Override
public int hashCode() {
int result = Objects.hash(label, score);
return 31 * result + Arrays.hashCode(values);
}
@Override
public String toString() {
return "Sample{label=" + label + ", score=" + score
+ ", values=" + Arrays.toString(values) + "}";
}
public static void main(String[] args) {
Sample a = new Sample(null, Double.NaN, new int[] {1, 2});
Sample b = new Sample(null, Double.NaN, new int[] {1, 2});
System.out.println(a.equals(a)); // true: reflexive even with NaN
System.out.println(a.equals(b)); // true
System.out.println(a.hashCode() == b.hashCode()); // true
System.out.println(a); // Sample{label=null, score=NaN, values=[1, 2]}
}
}The equals method compares the cheap primitive field first, so unequal objects usually return early. The order has no effect on correctness. toString uses Arrays.toString, because concatenating an array directly prints something like [I@1b6d3586.
Common mistakes
- Using
==ondoublefields. The result breaks reflexivity forNaN. - Using
Double.compareinequalsbut hashing the field in a way that distinguishes values it treats as equal. UseDouble.hashCode. - Forgetting to copy a mutable array in the constructor.
- Using a tolerance in
equals. This breaks transitivity and cannot be matched byhashCode. - Calling
field.equals(...)on a field that can benull.
Exercise
A class has the field double[] weights and the author wrote hashCode as return Objects.hash(name, weights);. Two instances with the same name and equal-content arrays are equals, yet a HashSet treats them as different elements. Why, and what is the fix?
Show answer
weights is a single array argument, so Objects.hash hashes the array's identity hash code. Equal-content arrays in different objects have different identity hashes, so equal objects get different hash codes and the HashSet usually looks in the wrong bucket. Compute the array's hash from its contents instead: 31 * Objects.hashCode(name) + Arrays.hashCode(weights).
Exercise
For a field double price, what does price == other.price give when both are Double.NaN, and what does Double.compare(price, other.price) == 0 give? Which keeps equals reflexive?
Show answer
== gives false, so an object holding NaN would not equal itself. Double.compare returns 0, so x.equals(x) stays true. Double.compare is the correct choice.
Exercise
A class stores int[][] board. Which pair of methods should equals and hashCode use for that field, and why is Arrays.equals not enough?
Show answer
Use Arrays.deepEquals(board, other.board) and Arrays.deepHashCode(board). Arrays.equals compares the inner arrays with equals, which is identity for arrays, so two boards with identical contents would be unequal.