How does Java HashMap store entries internally

前端 未结 3 524
生来不讨喜
生来不讨喜 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题