1

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?
4
  • 1
    What happened when you tried it? What does the javadoc of HashMap say? Commented Apr 12, 2016 at 18:09
  • The javadoc's 5th paragraph ("If many mappings...") says something about hashCode(), but I can't quite get the answer I need. Could point out the portion I need to read/focus on? Commented Apr 12, 2016 at 18:16
  • @sargas Your question doesn't mention hashCode. The hashCode is used to determine the index of the array the entry is stored in. If too many entries have the same hashCode, it will slow down the performance. Commented Apr 12, 2016 at 18:22
  • @PaulBoddington Correct. And I just found what I was looking for in the Map Interface documentation. Thanks. Commented Apr 12, 2016 at 18:26

2 Answers 2

5
  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.
Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't the map store the "hashCode()" of the object? And then compare the hashs with == ? If you implement equals() you are always supposed to implement hashCode for this specific reason
Yes, it does. But equal hashCodes doesn't mean that objects are equal. In the end, keys are compared with equals(). My point is that it doesn't tests if keys are ==, but if keys are equal.
3
  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)).

1 Comment

Your answer is very insightful to me. I ended up having to read the Map Interface's documentation to find this information (rather than the HashMap or LinkedHashMap ones).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.