Example
LinkedHashMap<Long, String> myHashMap = new LinkedHashMap<>();
myHashMap.put(new Long(1), "A Value");
Questions
- Is the key a reference or a copy?
- 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?
asked Apr 12, 2016 at 18:05
sargas
6,2408 gold badges56 silver badges70 bronze badges
2 Answers 2
- The map stores a a copy of the reference to the object passed as argument. No copy of objects is made.
- 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.
answered Apr 12, 2016 at 18:09
JB Nizet
694k94 gold badges1.3k silver badges1.3k bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Alex
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
JB Nizet
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.- The key is a reference to the same instance.
You will get
"A Value"back, becauseLonghas overriddenequals()(return value == obj.longValue()),hashCode()(return Long.hashCode(value)).
answered Apr 12, 2016 at 18:10
Andrew
49.9k15 gold badges99 silver badges145 bronze badges
1 Comment
sargas
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).
lang-java
HashMapsay?hashCode(), but I can't quite get the answer I need. Could point out the portion I need to read/focus on?hashCode. ThehashCodeis used to determine the index of the array the entry is stored in. If too many entries have the samehashCode, it will slow down the performance.