Java collection class (three) commonly used implementation class of Set collection

一.HashSet

The underlying data structure of HashSet uses 哈希表elements 无序(that is , it is not guaranteed that the order of the elements will not change) and 不可重复the time complexity of addition and deletion operations is O(1)that 可以且只可以there is a null value for the element .
In addition, the criterion for HashSet collection to determine whether two elements are equal is that the return value of the equals() method is true and the return value of the hashCode() method is also equal .
In fact, when an element is stored in the HashSet collection, the hashCode method is called to obtain its hashCode value, and then the storage location of the element in the memory is determined according to the hashCode value.

二.LinkedHashSet

The bottom layer of LinkHashSet 哈希表uniquely determines the storage location of the element to ensure uniqueness, while relying on the 链表realization of the element 插入有序排列(that is, the order of adding elements will be consistent with the order of accessing elements).
Demo code:

package package04_collection;

import java.util.Iterator;
import java.util.LinkedHashSet;

public class LinkedHashSetTest {
    
    
    public static void main(String[] args) {
    
    
        LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
        lhs.add(3);
        lhs.add(4);
        lhs.add(1);
        lhs.add(2);
        lhs.add(2);
        Iterator<Integer> iterator = lhs.iterator();
        while(iterator.hasNext()) {
    
    
            System.out.println(iterator.next());
        }
    }

}

In line with expected results:
Insert picture description here

Three.TreeSet

The underlying structure of the TreeSet collection is 红黑树(balanced binary search tree), which is used for implementation 对元素的排序(customizable sorting rules), and does not allow duplicate elements and cannot have null values .
Test code (natural order)

package package04_collection;

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetTest {
    
    
    public static void main(String[] args) {
    
    
        TreeSet<Integer> ts = new TreeSet<>();
        ts.add(2);
        ts.add(3);
        ts.add(4);
        ts.add(1);
        ts.add(1);
        Iterator<Integer> iterator = ts.iterator();
        while(iterator.hasNext()) {
    
    
            System.out.println(iterator.next());
        }
    }
}

Effect screenshot::
Insert picture description here
注意If the TreeSet element object is a reference data type, the compiler will report an error because it does not know what sort of elements should be used. At this time, you should use a custom sort, implement the Comparator interface and rewrite the compare() method .

Guess you like

Origin blog.csdn.net/m0_46550452/article/details/107257032