Sub topic 7
Comparing Wrappers Correctly
This chapter assumes you know the eight wrapper classes, understand autoboxing and unboxing, and have seen that Integer.valueOf caches small values. Here you will learn which comparison operator to use on wrappers, and why the wrong choice sometimes passes your tests and then fails later.
What == actually does with wrappers
The meaning of == depends on the static types of its two operands:
- If both operands are wrapper references,
==compares references. It asks whether they are the same object. - If at least one operand is a primitive, the other operand is unboxed and the values are compared numerically.
The cache means that reference comparison sometimes looks like value comparison. The next example shows all three cases.
public class MixedComparison {
public static void main(String[] args) {
Integer a = 1000;
Integer b = 1000;
int p = 1000;
System.out.println(a == p); // true: b is unboxed, numeric comparison
System.out.println(p == b); // true: same rule, operands swapped
System.out.println(a == b); // false on typical JVMs: two references
System.out.println(a.equals(b)); // true: compares values
System.out.println(a >= b && a <= b); // true: relational operators always unbox
}
}The line a == b is not guaranteed to print false. The language only requires that values from -128 to 127 be cached by valueOf. A JVM can cache more, for example through the -XX:AutoBoxCacheMax option. A comparison whose result depends on a JVM flag is a bug even when it happens to work.
The relational operators <, <=, > and >= have no reference meaning, so they always unbox. Only == and != are ambiguous. That is why code can use a < b safely and still break on a == b.
Which operator to use
For two wrapper objects, pick one of these:
| Goal | Use | Notes |
|---|---|---|
| Are the two values equal? | `a.equals(b)` | Throws `NullPointerException` if `a` is null. |
| Equal, and either may be null | `Objects.equals(a, b)` | Two nulls are equal; null and non-null are not. |
| Which value is smaller or larger? | `a.compareTo(b)` or `Integer.compare(x, y)` | Returns negative, zero or positive. |
| Compare a wrapper to a primitive | `a == p` | Safe, but throws if `a` is null. |
| Are these the same object? | `a == b` | Rarely what you want for wrappers. |
The flowchart below turns the table into a decision procedure.
equals is strict about the type
Integer.equals(Object) returns true only when the argument is an Integer with the same value. A Long holding 100 is never equal to an Integer holding 100. This catches people who mix numeric types, often through autoboxing of a literal.
public class EqualsTypeCheck {
public static void main(String[] args) {
Integer i = 100;
Long l = 100L;
System.out.println(i.equals(l)); // false: different classes
System.out.println(l.equals(100)); // false: 100 boxes to Integer, not Long
System.out.println(l.equals(100L)); // true: 100L boxes to Long
System.out.println(i.longValue() == l); // true: l is unboxed, numeric comparison
System.out.println(i.compareTo(100)); // 0
// System.out.println(i == l); // does not compile: Integer and Long are unrelated types
}
}Two points from this example:
l.equals(100)compiles becauseequalstakesObject. The compiler boxes100into anIntegerand the method returns false. Nothing warns you.i == lis a compile error, which is the one case where the compiler protects you. Forequalsit will not.
The same trap appears in collections. Set<Long> with set.contains(5) always returns false, because contains takes Object and the argument boxes to Integer. Write set.contains(5L).
Ordering with compareTo and compare
Every wrapper class implements Comparable for its own type, so Integer compares only to Integer. Each class also has a static compare method that works on primitives, for example Integer.compare(int, int) and Double.compare(double, double). Use these instead of subtraction. Subtraction overflows.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class OrderingExamples {
public static void main(String[] args) {
int x = Integer.MIN_VALUE;
int y = 1;
System.out.println(x - y); // 2147483647: overflow, wrong sign
System.out.println(Integer.compare(x, y)); // -1: correct
List<Integer> values = new ArrayList<>(List.of(300, 5, 128, 42));
Collections.sort(values); // natural order
System.out.println(values); // [5, 42, 128, 300]
values.sort(Comparator.reverseOrder());
System.out.println(values); // [300, 128, 42, 5]
List<Integer> withNull = new ArrayList<>();
withNull.add(3);
withNull.add(null);
withNull.add(1);
withNull.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
System.out.println(withNull); // [null, 1, 3]
}
}compareTo and compare return a negative number, zero or a positive number. Their contract does not promise -1, 0 or 1, so test with < 0, == 0 and > 0, never == -1. Plain Collections.sort on a list containing null throws NullPointerException, because natural ordering calls compareTo on the elements. Comparator.nullsFirst and Comparator.nullsLast wrap another comparator to handle that case.
Equality and null
Calling a.equals(b) when a is null throws. Comparing with == against a primitive unboxes the wrapper and throws too. Objects.equals handles both cases without an exception.
import java.util.Objects;
public class NullSafeEquality {
public static void main(String[] args) {
Integer maybe = null;
System.out.println(Objects.equals(maybe, 5)); // false
System.out.println(Objects.equals(maybe, null)); // true
System.out.println(maybe == null); // true: both sides are references, no unboxing
try {
System.out.println(maybe == 5); // 5 is a primitive, so maybe is unboxed
} catch (NullPointerException e) {
System.out.println("NullPointerException from unboxing");
}
}
}The expression maybe == null is safe because null is not a primitive. Both sides are references, so no unboxing happens. The expression maybe == 5 unboxes. A single wrapper value can therefore be fine in one comparison and throw in the next, depending only on what is on the other side.
A common refactoring mistake follows from this. Suppose a field changes from int to Integer to allow "missing". Every existing field == 5 still compiles, but it now throws when the field is null. Search for all comparisons when you make that change.
Collections use equals
List.contains, List.indexOf, Set.contains and Map.containsKey all use equals (and hashCode for hashed collections). They never use ==. This is why a HashMap<Integer, String> finds the key 1000 even though your lookup key is a different Integer object. It is also why the Long versus Integer mismatch above matters in collections.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CollectionEquality {
public static void main(String[] args) {
Map<Integer, String> names = new HashMap<>();
names.put(1000, "Ada");
Integer lookup = 1000; // a different object than the key
System.out.println(names.get(lookup)); // Ada: equals and hashCode are used
List<Long> ids = List.of(1L, 2L, 3L);
System.out.println(ids.contains(2)); // false: 2 boxes to Integer
System.out.println(ids.contains(2L)); // true
System.out.println(ids.get(1) == 2L); // true: unboxed, numeric comparison
}
}Double and Float need extra care
For Double and Float, equals and compareTo follow different rules from the primitive == operator. They are defined so that sorting and hashing stay consistent:
| Expression | Result | Reason |
|---|---|---|
| `Double.NaN == Double.NaN` | `false` | Primitive comparison follows IEEE 754. |
| `Double.valueOf(Double.NaN).equals(Double.NaN)` | `true` | `equals` compares the bit patterns. |
| `0.0 == -0.0` | `true` | Primitive comparison treats them as equal. |
| `Double.valueOf(0.0).equals(-0.0)` | `false` | The bit patterns differ. |
| `Double.compare(0.0, -0.0)` | positive | `-0.0` orders before `0.0`. |
| `Double.compare(Double.NaN, 1.0)` | positive | `NaN` orders after every other value, including infinity. |
For example, a == b on two double primitives and Double.valueOf(a).equals(b) can disagree. When you compare floating-point results for exact equality, decide which of the two behaviors you need. For computed values, neither is usually right. Compare with a tolerance instead, such as Math.abs(a - b) < 1e-9. A later chapter covers these special values in detail.
Other wrappers
- Boolean:
Boolean.valueOfalways returns one of the two constantsBoolean.TRUEandBoolean.FALSE. So==happens to work onBooleanvalues created throughvalueOfor autoboxing. ABooleancreated with the deprecated constructor is a separate object. Useequals, orBoolean.TRUE.equals(flag)when the flag may be null. - Character:
Character.valueOfcaches values from 0 to 127. - Byte: all 256 values are cached, so
==happens to work onBytevalues fromvalueOf. Do not depend on it. - Short and Long: values from -128 to 127 are cached, like
Integer. - Float and Double: there is no cache.
Double.valueOf(1.0) == Double.valueOf(1.0)is false in practice.
The cache is an optimization. Treat == on any two wrapper references as a bug unless you really mean object identity.
Common errors in review
- Comparing two
IntegerorLongfields with==, for exampleorder.getCustomerId() == other.getCustomerId(). - Calling
equalsbetween different wrapper types, or passing anintliteral to aLongcollection. - Writing a comparator as
(a, b) -> a - b, which overflows for large magnitudes. - Using
==against a literal on a wrapper that may be null. - Calling
equalson a possibly null left operand. Put the known non-null value on the left ("x".equals(s)), or useObjects.equals.
Exercise
A method has Long userId and Long ownerId, both loaded from a database, and either one may be null. Write the expression that is true only when both are present and equal, and say why userId == ownerId fails.
Show answer
Use userId != null && userId.equals(ownerId). If both could be null and you want that to count as equal, use Objects.equals(userId, ownerId). The expression userId == ownerId compares references because both operands are Long objects. Values above 127 are separate objects, so it returns false for equal ids. It also returns true for two nulls, which may not be what you want.
Exercise
What does each line print? Integer a = 50; Long b = 50L; System.out.println(a.equals(b)); System.out.println(b.equals(50L)); System.out.println(a.longValue() == b);
Show answer
The first line prints false, because Integer.equals needs an Integer argument and b is a Long. The second prints true, because 50L boxes to a Long with the same value. The third prints true, because a.longValue() is a primitive long, so b is unboxed and the values are compared numerically.
Exercise
Why is (x, y) -> x - y a risky comparator for Integer values, and what should replace it?
Show answer
The subtraction can overflow, for example Integer.MIN_VALUE - 1 wraps to a large positive number, so the comparator reports the wrong order. Replace it with Integer::compare or Comparator.naturalOrder(), which return the correct sign for every pair of values.