I believe everyone has used hashmap, but perhaps some beginners do not know how it works so that hashmap performance is very bad.
Why do you say that? The performance of the HashMap is very good under what circumstances will cause the performance drop so much.
First of all, say hashmap working principle:
working principle:
HAshmap is based on the hashing (hashing algorithm) principle, the caller obtains the object through the put () and get () methods. When the caller passes the key-value pair through put (), it calls the Hashcode method of the key-value pair to compute the hashcode value, and then finds the location of the bucket (bucket) based on the Hashcode value to store the object, and when the caller obtains the object through the Get () method, The corresponding key-value pairs are found by the Equals () method of the Key object, and then the value object is returned;
HASHMAP uses linked lists to solve the hash "collision" problem, when "collision" occurs, the object is stored in the next node of the list. HashMap stores the key value objects in each linked list node. When the hashcode values of the two different key objects are the same, they are stored in a linked list in the same bucket location, and get the value object to know the key value pairs by the Equals method of the key:
So here's the question, "What happens when the hashcode value of two-valued objects is equal." "
First of all, it is clear that a point of hashcode value equality does not determine the equality of two objects, if two different objects hashcode values are equal, so there is a "collision" at the time of storage, because the hashcode value is equal, so stored in the same location bucket list, In the worst case, all correspondence is stored in the bucket of the same location, so that the hashmap degenerate into a linked list, looking for data from O (1) to O (n), greatly reducing the performance of HashMap, In this case you should consider whether to continue using HashMap.
so the question is again, how to optimize for the above problem.
the way to optimize the above approach is to reduce "collisions" and how to reduce "collisions".
1.String, Interger such wrapper class as the HashMap key, and string is most commonly used because the string is immutable and final, and the Equals () and Hashcode () methods have been overridden. Other wrapper classes also have this feature. Immutability is necessary, because in order to compute hashcode (), the key value should be prevented from changing
2. Adhere to the rules of overriding equals () and Hashcode () methods when using custom objects as keys to ensure that different objects do not appear the same hashcode;
Well, to improve the hashmap advice on this, I hope to help the friends who need ...
Friendly tip: Java 8 has improved performance for HashMap