Example analysis of HashSet’s principle of removing duplicate values
The set in Java is a set that does not contain duplicate elements, specifically, E1 Element pair of equals (E2). Null is not allowed in set. Set cannot guarantee the order of elements in the set.
When adding an element to set, if the specified element does not exist, the addition is successful. That is, if the element E1 of (E = = null? E1 = = null: e.queals (E1)) does not exist in the set, E1 can be added to the set.
Taking an implementation class HashSet of set as an example, the following briefly introduces the principle of non repeated implementation of set:
The operation results are as follows:
Maybe you've seen the key. Yes, it's the equals method. This is still inappropriate. To be exact, it should be the equals and hashcode methods. Why? Let's change the customstring class to test:
Test results:
The return values of equals this time are all true, but the size of set is still 3
Let's continue to change
Look at the results again:
Just rewrite the hashcode method, not the equals method
Finally, change it again
Final results:
Yes, it is proved that the equals method and hashcode method need to be rewritten. Let's see the principle:
java. lnag. Hashcode convention in object:
1. During the execution of an application, if the information used for the comparison of the equals method of an object has not been modified, the hashcode method must be called multiple times for the object, and it must always return the same integer.
2. If two objects are equal according to the equals (objecto) method, calling the hashcode method of either object must produce the same integer result.
3. If two objects are not equal according to the equals (objecto) method, call the hashcode method of any of the two objects, and it is not required to produce different integer results. However, if it can be different, it may improve the performance of hash tables.
In HashSet, the basic operations are implemented at the bottom of HashMap, because the bottom of HashSet uses HashMap to store data. When adding an element to the HashSet, first calculate the hashcode value of the element, Then use this (hashcode of the element)% (the size of the HashMap set) + 1 to calculate the storage location of the element. If the location bit is empty, the element will be added; if it is not empty, use the equals method to compare whether the elements are equal, and if they are equal, they will not be added. Otherwise, find an empty bit to add.
The following is part of the source code of HashSet:
summary
The above is all about the example analysis of HashSet de duplication principle in this paper. I hope it will be helpful to you. Interested friends can continue to refer to other related topics on this site. If there are deficiencies, please leave a message to point out. Thank you for your support!