How does Java HashMap store entries internally

前端 未结 3 525
生来不讨喜
生来不讨喜 2020-12-10 15:00

Say you have a key class (KeyClass) with overridden equals, hashCode and clone methods. Assume that it has 2 primitive fields, a String (name) and an int (id).

Now y

相关标签:
3条回答
  • 2020-12-10 15:16

    Simply put, the HashMap is an object in your computer's memory that contains keys and values. Each key is unique (read about hashcode), and each key points to a single value.

    In your code example, the value coming out of your map in each case is the same because the key is the same. When you changed your key, there is no way to get a value for it because you never added an item to your HashMap with the mutated key.

    If you added the line:

    map.put("mutated", 2);
    

    Before mutating the key, then you will no longer get a null value.

    0 讨论(0)
  • 2020-12-10 15:23

    HashMap maintains a table of entries, with references to the associated keys and values, organized according to their hash code. If you mutate a key, then the hash code will change, but the entry in HashMap is still placed in the hash table according to the original hash code. That's why map.get(keyOriginal) will return null.

    map.keySet() just iterates over the hash table, returning the key of each entry it has.

    0 讨论(0)
  • 2020-12-10 15:30

    If you change the entry but not the hashCode, you are safe. For this reason it is considered best practice to make all fields in the hashCode, equals and compareTo, both final and immutable.

    0 讨论(0)
提交回复
热议问题