Card 01/ 08
equals, hashCode and toString: The Methods Every Object Inherits
You print an object and get Order@2a139a55; you compare two identical ones and get false.
Every Java class extends Object, and inherits three methods from it: equals, hashCode and toString. By default equals is true only for the very same object, hashCode gives each object its own number, and toString prints the class name and that number. A class that needs anything else overrides them.
You print an object to check a value and get Order@2a139a55. You compare two objects you know hold the same data and get false. Neither class declares a single method that would explain it; both results come from the inherited defaults:
| Method | Default behaviour | What that means |
|---|---|---|
equals(Object) | this == other | Equal means the very same object, never the same contents |
hashCode() | A number chosen per object | Two objects with identical fields usually get different numbers |
toString() | Class name, @, hash in hexadecimal | Order@2a139a55 |
Order a = new Order("AB-1", 10);
Order b = new Order("AB-1", 10);
System.out.println(a);
System.out.println(a.equals(b));Order@2a139a55
falseThe number after the @ means nothing to a reader and can change from one run to the next. What it tells you is that toString was never overridden.
The defaults are not wrong. They are the only answers a class called Object could give, because it has no idea which of your fields decide identity.
So the three are yours to write, and the decision to leave them alone is a decision too: it says that two of these objects are never equal, however identical their contents.
← → move through sections and cards