Hash collapse and avoid method

xiaoxiao2021-03-06  61

First look at the following example, if you can not hesitate to answer all the reply, explain that you have basically understood the HashMap.

Import java.util.map;

Import java.util.hashmap;

Import java.util.set;

Import java.util.hashset;

Class hashfail

{

Public static void main (string [] args)

{

Map map = new hashmap ();

Key K = New Key (10);

Map.put (k, "value"); // Insert a key: 10

System.out.println (map.get (k)! = Null); // It is obvious to TRUE

K.I ; // Key place, Key changes

System.out.println (Map.get (k)! = Null); //?

System.out.println (map.get (new key (10))! = Null); //?

System.out.println (map.get (new key (11))! = Null); //?

For (int i = 0; i <20; i ) map.put (new object (), new object ()); // Add some useless information, resulting in the rehash process

System.out.println (Map.get (k)! = Null); //? System.out.println (map.get (new key (10))! = Null); //? System.out.println Map.get (new key (11))! = null; //?

K.i -; // Here, Key will change back.

System.out.println (Map.get (k)! = Null); //? System.out.println (map.get (new key (10))! = Null); //? System.out.println Map.get (new key (11))! = null; //?

} Static class key {Int i; key (int i) {this.i = i;} public boolean equals (object obj) {RETURN I == (key) Obj) .i;} public int.come () {Return }};

Because modifying the value of Key, this Key's hashcode has also changed, so when calling the GET method, you can't find it, when it is rehash

Can you recover, the results cannot be recovered, and it will be known that HashMap is known. When he generated an entry, he used Key's Hashcode and did not change as Key changes. So after inserting a Key-Value in a HashMap, change the value of Key.

This caused the key of the Hashcode to change, then this value cannot be obtained.

Avoid ways:

1. Use a non-variable object as a key such as String, Integer, and more.

2. Do not retain reference to Key, such as above

Key K = New Key (10);

Map.put (k, "value");

转载请注明原文地址:https://www.9cbs.com/read-90734.html

New Post(0)