Object Equality: Identity and Meaning
When you compare two objects, you need to decide what equal means. Are you checking whether two variables refer to the same object, or whether separate objects represent the same value? This distinction matters when checking duplicate bookings, comparing identifiers, or testing results. Java and Python express these questions differently, so transferring an operator from one language to another can change your program's meaning.
Two questions about sameness
Object identity means being the very same object. Two variables can refer to one object; these shared references are called aliases. Assigning an existing object reference to another variable does not create a second object.
Value equality means satisfying the comparison rule chosen for the object's type. For example, two seat objects might represent the same seat when both their row and seat number match. They can satisfy that rule while remaining separate objects.
For a design that compares a selected key K, the governing rule is:
Here, K(a) means the field or combination of fields selected for comparison. Choosing that key is a design decision: matching one field is sufficient only when that field captures the intended meaning of equality.
In the diagram, a and b share an identity. The object referenced by c is separate, even though its code matches. If equality is defined by code alone, all three references designate equal values.
Read the operation in its language
For Java object references, == tests identity. Calling a.equals(b) uses the equality method implemented by the object's class. The implementation inherited from Object also tests identity; meaningful value comparison requires an appropriate implementation. Java's String class already provides text-based equality.
Example: After the following Java statements, first == second is false, but first.equals(second) is true.
String first = new String("arrival");
String second = new String("arrival");Each new expression creates a separate object. Their text nevertheless matches. Do not infer identity from matching printed output.
Python uses is for identity. Its == operator invokes the language's equality protocol, which uses the special method __eq__. An ordinary user-defined class that supplies no custom equality behavior compares by identity by default.
Question | Java object references | Python objects |
|---|---|---|
Same object? | a == b | a is b |
Equality according to the type? | a.equals(b) | a == b |
Where is custom equality defined? | Override equals(Object other) | Define __eq__(self, other) |
In Java, calling .equals through a null reference causes an exception. A non-null object's correctly implemented equals returns false when compared with null. In Python, use is None to check for the special missing-value object.
Make the equality rule coherent
A conventional equality rule is reflexive: an object equals itself. It is symmetric: reversing the operands preserves the result. It is also transitive: if a equals b and b equals c, then a equals c. Repeated comparisons should agree while the relevant information remains unchanged.
A proximity test can fail transitivity. Being close enough to a middle value does not necessarily make two endpoint values close enough to each other. Such a test may be useful, but it should not automatically become an object's equality rule.
When implementing Python's __eq__, return NotImplemented for operand types the method does not support, allowing Python to continue its comparison protocol. If objects participate in hash-based collections, equal objects must also have equal hash values. Unequal objects may still share a hash value; a hash match does not establish equality.
What to remember
- Identify whether the task asks about identity or value equality.
- Java reference == and Python is test identity.
- Java equals and Python == depend on the type's equality behavior.
- Check the selected fields and the equality rule's consistency.
Example: Comparing Seat Bookings
A theatre system uses a Java Seat class. Its equals(Object other) method returns true for another Seat exactly when both row and seat number match. Row text is compared by content. No fields change during this problem.
Seat a = new Seat("N", 14);
Seat b = new Seat("N", 14);
Seat c = a;
Seat d = new Seat("S", 14);Each new Seat expression creates a separate object. Work through the three parts before revealing their solutions.
a) Compare object identities
Determine the results of a == b, a == c, and b == d.
Object identity means being the same particular object. First trace the assignments rather than comparing the seat fields. The variable assigned to c is ________, so those two variables refer to one object.
The declarations of a, b, and d each use a separate new expression. Consequently, a and b refer to different objects, and b and d also refer to different objects.
The results are a == b: false; a == c: true; b == d: false.
b) Compare represented seats
Determine the results of a.equals(b), a.equals(c), and b.equals(d).
Value equality means satisfying the class's specified comparison rule. Here, both the row and the seat number must match.
Start with a.equals(b). Object b has row ________ and seat number ________. These match both fields in a, so this comparison is true despite the separate identities.
Next, a.equals(c) is true because c refers to a itself and its fields therefore match.
Finally, object d has row ________. Its seat number matches the number in b, but its row does not. Matching the number alone is insufficient.
The results are a.equals(b): true; a.equals(c): true; b.equals(d): false.
c) Count distinct represented seats
If duplicate represented seats are counted only once using this equality rule, how many distinct seats occur among a, b, c, and d?
Group references by the row-and-number pair selected by the equality rule. References a, b, and c all represent seat N14, so they contribute one distinct seat. Reference d represents seat S14 and contributes one more.
The count is 1+1=2. There are four variables and three created objects, but those counts answer different questions from the number of represented seats.
The final answer is 2 distinct seats.
A Java check-in system creates the following references. Complete every table cell with true or false. Same object means reference identity; equal text means the result of calling the first reference's equals method with the second reference.
String x = new String("platform-8");
String y = new String("platform-8");
String z = x;
String w = new String("platform-9");| Reference pair | Same object | Equal text |
| x and y | ||
| x and z | ||
| y and z | ||
| z and w |
A Python sensor program defines token equality by token code. How many of the five listed comparisons evaluate to True? Answer as an exact integer count of comparisons, with no decimal places.
class Token:
def __init__(self, code):
self.code = code
def __eq__(self, other):
if type(other) is not Token:
return NotImplemented
return self.code == other.code
a = Token(25)
b = Token(25)
c = a
d = Token(40)The five comparisons are:
a == b
a is b
a is c
b == d
c == b