What they're testing
Whether you know the contract between the two, and in which order hash-based collections use them.
The short answer~30 seconds
Because the contract says: objects equal under equals() MUST have the same hashCode(). HashMap locates a bucket by hash first and only then compares with equals() inside it — so with different hashes it looks in the wrong bucket and never reaches equals(). The result is that you put an object and get with an equal one, and receive null.
The long answer
The converse isn't required: equal hash codes don't imply equal objects. That's a collision, and it's entirely legal — HashMap resolves it by comparing with equals() inside the bucket. Which means a hashCode() that always returns a constant is still CORRECT under the contract; it just turns the map into a linked list and every operation into O(n).
The more dangerous trap is computing the hash from MUTABLE fields. You put the object in a HashSet, mutate that field, the hash changes, and the object stays in its old bucket — now contains() returns false for the very object sitting in the set. That's why map keys should be immutable, and a very practical reason to reach for record from Java 16 onward.
// record sinh sẵn equals/hashCode/toString từ các thành phần
record UserId(String tenant, long id) {}
var set = new HashSet<UserId>();
set.add(new UserId("acme", 7));
set.contains(new UserId("acme", 7)); // true
// Lớp chỉ ghi đè equals: biên dịch được, và hỏng ngay
class Bad { int id; public boolean equals(Object o) { /* … */ } }
var m = new HashMap<Bad, String>();
m.put(a, "x");
m.get(b); // null, dù a.equals(b) là trueWhat they'll ask next
?== versus equals()?
== compares references (or values for primitives); equals() compares content however the class defines it. With String, == can be accidentally true thanks to the string pool, which is exactly what convinces beginners it always works.
These lose points
- Saying "hashCode returns the memory address". It doesn't, and HotSpot caches the computed value in the object header.