It is mainly to record the hashMap interview questions asked in an interview, so as to prevent future encounters or not
question:
HashMap<String, String> map = new HashMap<>();
String a = new String("1");
String b = new String("1");
map.put(a, "value");
then map Are .get(a) and map.get(b) equal
I thought it was unequal at first, because we all know that when map uses an object as a key, it always uses the address value of the object as the key. Then a and b are new, and the address values are obviously not equal. I thought it should be unequal, but after running it, I found that it was actually equal
I didn't understand it for a moment, so I looked at the source code. Start with the put method of map to see if there is any change when it is the basic data type
Find the reason: start with the get source code of HashMap
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) ==
null ? null : e.value;
}
Here it is found that the key is hashed during get. So it is inferred that the hash values of the two String objects should be the same. Then, after reading the hash source code of String, you can search for relevantString 的hashCode算法
Finally, it is concluded that the hashCode of String is calculated according to the value of String. So as long as it is the same value, the hashCode is the same
So here comes a point that is often said in interviews:
The hash code of a string is only counted once, and it is cached, so there is no need to repeat work in the future!
Integer is simpler, hashCode is the value
public int hashCode() {
return Integer.hashCode(value);
}
public static int hashCode(int value) {
return value;
}
So far - conclusion
HashMap still gets the same data because the hash value of the key is equal.
String and Integer are both equal in value and hashCode, so hashMap considers them to be the same key!
To judge whether the key of HashMap is repeated, it depends on whether the hash value of the key is repeated!