MsA
MsA

Reputation: 2979

Can we use instances of Object class as keys in HashMap

The question is simple as title:

Can we use instances of Object class as keys in HashMap?

I am not talking about using any custom class as key, but using Object class instances as a key. Do we need to take any precautions if at all we can use it?

Upvotes: 0

Views: 72

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Yes, you are allowed to use instances of Object as a map's key:

Map<Object, SomeOtherType> myMap = new HashMap<>();

But this may be a dangerous thing to do, as this means that objects of any type can be used as a key object, including objects that are not immutable, and if a key object is used that is an object whose .equals(...) or .hashCode() can later change, expect some bad side-effects with maps that break. This is true for any map where the key is potentially mutable.

Per the Map API:

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.

So in sum: yes, this is possible, but don't do it

Upvotes: 3

Related Questions