Common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most equality bugs compile without a warning and only give wrong answers later: a search that finds nothing, a duplicate that gets in. They come from a small set of mistakes, and each has a fixed cure.
Mistakes and fixes at a glance
The slip that hides longest in a new equals(): a cast with no class check. (Student) obj works while you compare Students, then crashes the day someone passes a String.
Example 1 · Mistake: a cast with no class check
class Student { String name;
Student(String name) { this.name = name; }
@Override public boolean equals(Object obj) { Student other = (Student) obj; return name.equals(other.name); }}
public class CastBugDemo { public static void main(String[] args) { Student s = new Student("Aarav"); System.out.println(s.equals(new Student("Aarav"))); System.out.println(s.equals("Aarav")); }}true Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class Student (java.lang.String is in module java.base of loader 'bootstrap'; Student is in unnamed module of loader 'app') at Student.equals(CastBugDemo.java:10) at CastBugDemo.main(CastBugDemo.java:19)
What this code does
- Comparing with another Student works, so the bug hides at first.
- Comparing with a String crashes at the cast. The
nullandgetClass()checks of the recipe makeequals()returnfalseinstead.
Review: Write your own equals() (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:
cannot find symbol ... variable o of type Object→ anObjectreference can call onlyObjectmethods; use the real class as the type. Review: The Object class (opens in a new tab)- Printing shows
Student@76ed5528, or javac saysreturn type void is not compatible with Stringorweaker access privileges→ write@Override public String toString()and return the text. Review: toString() (opens in a new tab) a == bisfalsefor two objects with the same data →==checks identity; compare data withequals(), and use==only fornullchecks. Review: == compares references (opens in a new tab)equals(Student other)works with Student variables but not withObjectones → the parameter must beObject;@Overridecatches it. Review: Write your own equals() (opens in a new tab)NullPointerExceptioninsideequals()→ compare fields that may benullwithObjects.equals. Review: Write your own equals() (opens in a new tab)- Equal objects not found, or stored twice →
hashCode()is missing or uses a fieldequals()ignores; returnObjects.hash(...)with the same fields. Review: hashCode() (opens in a new tab)
double fields and money
A double stores most decimals only approximately: 0.1 + 0.2 is really 0.30000000000000004. An equals() that compares computed double prices then gives wrong answers.
Example 2 · double prices vs whole paise
class ItemD { double price;
ItemD(double price) { this.price = price; }}
class ItemP { int paise;
ItemP(int paise) { this.paise = paise; }}
public class MoneyDemo { public static void main(String[] args) { ItemD a = new ItemD(0.1 + 0.2); ItemD b = new ItemD(0.3); System.out.println(a.price + " vs " + b.price); System.out.println(a.price == b.price); System.out.println(Double.compare(a.price, b.price) == 0);
ItemP c = new ItemP(10 + 20); ItemP d = new ItemP(30); System.out.println(c.paise == d.paise); }}0.30000000000000004 vs 0.3 false false true
What this code does
- The computed
doubleis not exactly 0.3, so==and evenDouble.comparesay "different". - Storing 10 + 20 paise as
intis exact, so prices compare correctly.
For money, store whole paise in an int or long: Rs. 49.99 becomes 4999. Whole numbers are exact, so == and Objects.hash just work. When a field really must be a double, compare it with Double.compare(a, b) == 0, but choose the right type first.
Fields that change, and identity by id
A hash-based collection files an object under its hash code at the time it was added. Change a field used in hashCode() afterwards, and the very same object can no longer be found.
Example 3 · Mistake: changing a field after adding the object
import java.util.Objects;
class Student { String name; int roll;
Student(String name, int roll) { this.name = name; this.roll = roll; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Student other = (Student) obj; return roll == other.roll && name.equals(other.name); }
@Override public int hashCode() { return Objects.hash(roll, name); }}
class TinyTable { Object[][] items = new Object[4][5]; int[][] hashes = new int[4][5]; int[] sizes = new int[4];
int bucketOf(int hash) { return Math.abs(hash % 4); }
void add(Object o) { int h = o.hashCode(); int b = bucketOf(h); items[b][sizes[b]] = o; hashes[b][sizes[b]] = h; sizes[b]++; }
boolean contains(Object o) { int h = o.hashCode(); int b = bucketOf(h); for (int i = 0; i < sizes[b]; i++) { if (hashes[b][i] == h && items[b][i].equals(o)) { return true; } } return false; }}
public class ChangedFieldDemo { public static void main(String[] args) { Student s = new Student("Aarav", 12); TinyTable t = new TinyTable(); t.add(s); System.out.println("before: " + t.contains(s));
s.name = "Aarav Kumar"; System.out.println("after: " + t.contains(s)); }}before: true after: false
What this code does
TinyTableis the small hash table from the hashCode() lesson. It saved the hash code of"Aarav"when the student was added.- After the name changes, the new hash code no longer matches the saved one, so the table cannot find the very same object.
Example 4 · The safe design: identity by a final id
import java.util.Objects;
class Product { final int id; String name; int pricePaise;
Product(int id, String name, int pricePaise) { this.id = id; this.name = name; this.pricePaise = pricePaise; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Product other = (Product) obj; return id == other.id; }
@Override public int hashCode() { return Objects.hash(id); }
@Override public String toString() { return "#" + id + " " + name + " Rs. " + (pricePaise / 100); }}
public class ProductIdDemo { public static void main(String[] args) { Product p = new Product(501, "Notebook", 6000); int before = p.hashCode(); p.pricePaise = 5500; System.out.println(p); System.out.println(before == p.hashCode()); System.out.println(p.equals(new Product(501, "Notebook (A4)", 6500))); }}#501 Notebook Rs. 55 true true
What this code does
- Equality and the hash code depend only on the
finalid, so a price change does not move the product to another bucket. - Another object with id 501 is the same product, even with a different name or price.
So base equals() and hashCode() on fields that never change, usually a final id: a product id, a customer id, an admission number. A product whose price changes is still the same product. Immutable objects (opens in a new tab) takes this further.
equals(): "Which fields tell me this is the same real-world thing?"Spot the bug
Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask: is it identity or data, does the header match Object exactly, and do equals() and hashCode() use the same fields?
Find the bug
Find the equality bug
Select the line that is wrong.
Find Diya (roll 7) in the class list.
Round 1 of 5Trace before you guess
When an equality result surprises you, trace it. First ask "the same object?" for ==, then follow equals() line by line, then check whether a field changed.
Trace the code
Trace == and equals()
Variables
- a
- object 1, no 12
Output
(nothing printed yet)Line 15a points to a new Seat with no = 12.
Finish up
Mark complete & continue
Next: Must-do problems: Object Class and Equality