Sub topic 12
Comparing Object Identity and Logical Equality
Two Java objects can hold the same information without being the same object. This difference matters when you compare values, search a collection, or decide whether an item is already present.
This chapter assumes you have worked with classes, objects, methods, and references. A reference is a value that points to an object. A method is an action you can call on an object.
Two ways to compare objects
Object identity asks: “Are these references pointing to the very same object?”
Logical equality asks: “Do these objects count as equal according to their values?” The answer depends on how their class defines equality.
Java provides two common ways to compare objects:
| Comparison | What it asks |
|---|---|
| `a == b` | Do `a` and `b` refer to the same object, or are both `null`? |
| `a.equals(b)` | Does the object referenced by `a` consider `b` equal? |
The symbol == is an operator, a symbol that performs an action. With object references, it checks identity. With primitive values such as int, it compares the values instead.
For example, 3 == 3 is true. But two separate objects can contain matching values while a == b is false.
Compare strings
A String is a Java object that holds text. Its equals method compares the text, including letter case.
The following program creates two separate strings with the same text. It also creates another reference to the first string.
Save the program as EqualityBasics.java. Compile it with javac EqualityBasics.java, then run it with java EqualityBasics.
import java.util.Objects;
public class EqualityBasics {
public static void main(String[] args) {
String first = new String("hello");
String alias = first;
String second = new String("hello");
String missing = null;
System.out.println(first == alias);
System.out.println(first == second);
System.out.println(first.equals(second));
System.out.println(first.equals("Hello"));
System.out.println(missing == null);
System.out.println(Objects.equals(missing, second));
System.out.println(Objects.equals(missing, null));
}
}The program prints these results in order:
| Comparison | Result | Reason |
|---|---|---|
| `first == alias` | `true` | Both references point to the same object. |
| `first == second` | `false` | The strings are separate objects. |
| `first.equals(second)` | `true` | Both strings contain `hello`. |
| `first.equals("Hello")` | `false` | `String.equals` checks letter case. |
| `missing == null` | `true` | `missing` does not refer to an object. |
| `Objects.equals(missing, second)` | `false` | One reference is `null`; the other is not. |
| `Objects.equals(missing, null)` | `true` | Both references are `null`. |
The following diagram shows the first three references. alias is an alias: another reference to an object that already has a reference.
This example uses new String to make the separate objects clear. In everyday Java code, you will often write strings as text in quotes, such as "hello". Java may share string objects for such text, so == can sometimes appear to work for comparing text. Use equals when you want to compare the text itself.
Comparing when a reference might be null
null means that a reference does not point to an object. You can use == null to check for it. Two null references also compare as equal with ==, although neither points to an object.
You cannot call a method on null. If missing is null, calling missing.equals(second) causes a NullPointerException. An exception is a problem reported while the program runs. Here, it tells you that the program tried to use null as an object.
Objects.equals(a, b) is a null-safe alternative. It is provided by java.util.Objects and works like this:
- If both references are
null, it returnstrue. - If only
aisnull, it returnsfalse. - Otherwise, it calls
a.equals(b).
For a well-written equals method, a non-null object is not equal to null. This makes Objects.equals useful when either reference might be missing.
What does equals do for your own class?
Every Java class has an equals method. By default, it checks identity, much like ==. Two separate objects are therefore not logically equal just because their fields hold matching values.
A field is a value stored in an object. To compare selected fields instead, a class can override equals. Overriding means providing a new version of an inherited method. The class decides which values matter for equality.
For example, suppose a ticket is identified by its number. In this example, two tickets with the same number should count as equal.
Save this program as TicketDemo.java. Compile it with javac TicketDemo.java, then run it with java TicketDemo.
import java.util.HashSet;
final class Ticket {
private final int number;
Ticket(int number) {
this.number = number;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Ticket)) {
return false;
}
Ticket ticket = (Ticket) other;
return number == ticket.number;
}
@Override
public int hashCode() {
return Integer.hashCode(number);
}
}
public class TicketDemo {
public static void main(String[] args) {
Ticket first = new Ticket(7);
Ticket sameNumber = new Ticket(7);
Ticket differentNumber = new Ticket(8);
System.out.println(first == sameNumber);
System.out.println(first.equals(sameNumber));
System.out.println(first.equals(differentNumber));
System.out.println(first.equals(null));
HashSet<Ticket> tickets = new HashSet<Ticket>();
tickets.add(first);
tickets.add(sameNumber);
System.out.println(tickets.size());
System.out.println(tickets.contains(new Ticket(7)));
}
}The results are false, true, false, false, 1, and true, in that order.
Follow the equals method
The method receives other as an Object. Object is the general parent class of Java classes, so the argument can refer to many kinds of object.
The method checks the comparison in stages:
this == otherchecks whether both references point to the current ticket. If so, they are equal.other instanceof Ticketchecks whetherotheris aTicket. It is alsofalsewhenotherisnull.(Ticket) otheris a cast: it lets the program useotheras aTicketafter the type check.- The final line compares the two ticket numbers. Since
numberis anint,==compares its numeric value.
The @Override marker tells the compiler to check that the method really overrides a method from a parent class. It helps catch mistakes in the method’s name or parameter list.
The class is marked final, which means no other class can extend it. This keeps the example’s equality rule from having to account for subclasses with extra fields.
Why hashCode must agree with equals
A hash code is an integer that helps some collections find objects. A collection is an object that holds other objects. The example uses a HashSet, a collection that keeps at most one item for each equal value.
When you override equals, also override hashCode. The important rule is:
- If two objects are equal according to
equals, they must have the same hash code. - Two objects with the same hash code do not have to be equal.
Ticket.hashCode uses the ticket number, just as Ticket.equals does. The two tickets numbered 7 are equal and have the same hash code. The HashSet therefore keeps one of them, and its size is 1. It can also find a newly created ticket numbered 7.
If equal objects produce different hash codes, a HashSet may fail to recognize them as equal. This can lead to unexpected duplicates or failed searches.
Rules for a useful equals method
Java expects an equals method to follow a contract: a set of rules that callers can rely on. For non-null objects, the main rules are:
- An object equals itself.
- If
a.equals(b)istrue, thenb.equals(a)must also betrue. - If
aequalsbandbequalsc, thenamust equalc. - Repeating a comparison gives the same result as long as the values used in the comparison do not change.
- An object does not equal
null.
Choose the fields that represent logical equality for your class, and use the same choice consistently. In Ticket, only the number matters because that is the rule the example chose.
A common array surprise
An array is an object that holds a fixed number of values. Arrays do not compare their contents with equals; their equals method uses identity.
For one-dimensional arrays, use java.util.Arrays.equals(a, b) when you want to compare corresponding contents. For example, two separate int arrays containing 1 and 2 compare as equal with that method, even though a == b is false.
Exercises
Exercise
Two separate String objects both contain "cat". What do == and equals report?
Show answer
== reports false because the objects are separate. equals reports true because their text matches.
Exercise
If a and b are both null, what does Objects.equals(a, b) return? Can you call a.equals(b)?
Show answer
Objects.equals returns true. You cannot call a.equals(b) because calling a method on null causes a NullPointerException.
Exercise
A class compares two objects as equal using their ID field. What must be true of their hash codes?
Show answer
The equal objects must have the same hash code. A common approach is to calculate the hash code from the ID field.