sargas
sargas

Reputation: 6180

Java HashMap and Object keys

Example

LinkedHashMap<Long, String> myHashMap = new LinkedHashMap<>();
myHashMap.put(new Long(1), "A Value");

Questions

  1. Is the key a reference or a copy?
  2. If I write String aValue = myHashMap.get(new Long(1));, will I get "A Value" back? Or have I just queried for a different object (reference) and therefore I'll get an error?

Upvotes: 1

Views: 75

Answers (2)

Andrew
Andrew

Reputation: 49656

  1. The key is a reference to the same instance.
  2. You will get "A Value" back, because Long has overridden

    • equals() (return value == obj.longValue()),
    • hashCode() (return Long.hashCode(value)).

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 692121

  1. The map stores a a copy of the reference to the object passed as argument. No copy of objects is made.
  2. Yes, you will get "A Value" back, as documented. A Map compares its keys with equals(), not == (except for IdentityHashMap). You could test that pretty easily, BTW.

Upvotes: 5

Related Questions