Equality in Java
== on primitives and on references, equals and hashCode, records, strings, boxed numbers and doubles: which comparison each kind of value needs.
Ask what kind of value is on each side.
- Two primitives (
int,char,boolean) →==compares the values. Fine. - Two
doubles that came out of a calculation → never==; compare the difference with a tolerance, or useBigDecimalfor exact decimals. - Two references →
==asks "the same object?", which is rarely the question.equalsasks "the same value?". - Strings → always
equals(orequalsIgnoreCase). Text from input,substringor+is a new object, so==fails on equal text. - Boxed numbers (
Integer,Long) →equals.==happens to work from -128 to 127, because those boxes are cached, and fails above. - Your own class → a record gets value equality for free. A class must override
equalsANDhashCodetogether, orHashSetandHashMapmisbehave. - Sorted collections (
TreeSet,TreeMap) → they usecompareToor theComparator, notequals, to decide what counts as a duplicate.
== and what it compares
Section
Comparison operators
== and != on primitives.
Section
Values and references
A reference variable holds an arrow to an object; == compares arrows.
Term
reference
What a reference variable holds, and what == compares for objects.
Term
tolerance
Example
Math.abs(total - 0.3) < 1e-9How close two doubles must be to count as equal.
Value equality
Section
Comparing strings
equals compares text; == compares references.
Term
string pool
Why == sometimes seems to work on string literals, and why that can't be relied on.
Section
toString, equals and hashCode
Overriding equals correctly, and why hashCode must follow.
Example
equals without hashCode, and set.contains(copy) returns false.Equal objects must have equal hash codes.
Section
Records
Value equality generated from the components.
Example
Integer a = 128, b = 128; then a == b is false, a.equals(b) is true.The -128 to 127 boxes that make == on Integers look like it works.
Ordering instead of equality
compareTo's order, which sorted collections use to spot duplicates.
Section
Sets
HashSet uses equals and hashCode; TreeSet uses compareTo.