简体   繁体   中英

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?
  1. The map stores aa 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.
  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) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM