Sobes.tech
Middle

What does the get() method of HashMap return if equals and hashCode methods are not overridden?

sobes.tech AI

Answer from AI

null will be returned if the key used for lookup is not the same object (has the same reference equality) as the one used when inserting the element.

The reason is that HashMap uses a combination of hashCode() and equals() to determine "equality" of keys. If these methods are not overridden, the implementations from Object are used.

  1. Object.hashCode() usually returns a value based on the memory address of the object, which is unique for each instance.
  2. Object.equals() simply checks reference equality (this == obj).

Thus, for HashMap.get() to find an element when using the default equals and hashCode, both conditions must match:

  • Hash codes (Object.hashCode()) must be equal, which is very unlikely for different objects.
  • The objects must be reference-equal (Object.equals()), meaning it must be the same instance of the object.

If you put an object into a HashMap, and then try to retrieve it using another object with the same field values (but not the same instance), hashCode and equals by default will consider them different, and get() will return null.

What does the get() method of HashMap return if… - sobes.tech