HashSet in Java, how does it work internally?

 HashSet is a collection in Java, which is implemented based on a hash table and used to store a set of unique elements. The inner working of HashSet is as follows:

  1. Hash table data structure

  HashSet internally uses a hash table to store elements. A hash table is an array, and each element is stored in a specific position of the array, which is determined by the element's hash code (hash code). The hash code is calculated by the hashCode() method of the element.

  2. Add elements

  When you add an element to HashSet, HashSet first calculates the hash code of the element. It then uses the hash code to determine where to store it in the hash table. If the location is empty, then the element will be stored directly in this location. If the location is not empty (that is, a hash collision occurred), the HashSet uses a linked list or a more efficient data structure, such as a red-black tree (introduced in Java 8 and later) to store the values ​​​​with the same hash code. element.

  3. Ensure uniqueness

  HashSet ensures that there will be no duplicate elements in it. It checks the uniqueness of an element by comparing its hashcode with the equals() method. If two elements have the same hash code, HashSet will call their equals() method to further compare whether they are equal. If equals() returns true, the HashSet will not store the second identical element.

1693276078649_How does Hashset work internally.jpg

  4. Query elements

  When we query whether an element is contained in HashSet, HashSet will calculate the hash code of the element, and find the storage location according to the hash code. It then uses the equals() method to check for identical elements.

  5. Delete elements

  When we try to delete an element from HashSet, HashSet will calculate the hash code of the element, and then find the storage location. If an element is found, it will be removed. If there is a hash collision, HashSet will find and delete the corresponding element in the linked list or red-black tree.

  It should be noted that HashSet does not guarantee the order of elements, and the storage order of elements is related to their hash codes. If you need an ordered collection, consider using a LinkedHashSet, which maintains the insertion order of elements, or a TreeSet, which sorts elements by their natural order or a custom comparator.

 

Guess you like

Origin blog.csdn.net/Blue92120/article/details/132556563