I don't understand what the two PhoneNumber instance he talks about.
The first one is the one you used for insertion.
m.put(new PhoneNumber(707, 867, 5309), "Jenny"));
The second instance is the one used for retrieval.
m.get(new PhoneNumber(707, 867, 5309)); // Notice the use of "new"
Also I look for this object again, which should return the same hashcode even if it inherits the hashCode method from Object Class.
That's incorrect. The default implementation of hashCode()
in Object
class returns distinct integers for distinct objects because it is implemented by converting the internal address of the object into an integer. Hence, the hash code check fails there.
If on the other hand, you had tried to retrieve the PhoneNumber
using the same instance
PhoneNumber phoneNum = new PhoneNumber(707, 867, 5309);
m.put(phoneNum, "Jenny"));
m.get(phoneNum); // Not NULL
The hash code check would pass (since, you've used the same object that was inserted before) and the equals()
as well. This of course isn't the recommended approach because we're far more likely to use a different key object than the one used for insertion.
The key used would, however, be meaningfully equivalent (like a different String object but whose text is the same) and hence providing a hashCode()
implementation is required for the match and retrieval to happen correctly.
Also see: Checking for and Removing elements in Java HashMap