First you need to understand that Java Hastset is actually implemented in a hash table, the size of the hash table is by default size 16 (also known as the number of hashes), and the load factor is 0,75 (the following explains what the load factor is).
The principle of HashSet: When add an element a, first get the hash code (Hashcode method) of the element, assuming the hash code is 400, then the hash code to the number of hash box modulo, 400%16=0;
0 represents the first element, and then element A and the first list in the hash table (modulo 0), so here is the first list of each element to compare, (compare by equals ~ ~) If the same element is not found in the list, then element A is added to the list, If an element is found to be the same as element A, it means that the element already exists in set, and element A is not added.
Capacity expansion principle: Here first explain what is the load factor, when the number of non-empty hashes in the hash table is divided by the number > load factor of all the hashes, the HashSet is hashed, the hash size is X2 on the original basis, all the elements are hashed, and the new hash table is obtained. The previous hash table is useless ~ ~. For a simple example: assuming that the hashset hash table size is now 8, the load factor is 30 of the elements in the 0,75,hastset, the first list contains 14 elements, the second linked list is empty (for an empty record 0), and so on, respectively: 14 0 0 4 2 2 2 6
Now set adds the 31st element b,b hash value to 9,9%b=1, so the element B is compared to the elements in the second list, and the second linked list is empty, so element B is added to the second list. At this point, the number of elements in the hash list are 14 1 0 4 2 2 2 6, the Non-empty chain table divided by the whole list size is 7/8>0.75, then it will be hashed, the size of the hash table is 8x2=16. When the element is increasing, the expansion is expanded.