Detailed Set Collection—Set Collection

Set interface

The Set interface is a sub-interface of Collection, and the set interface does not provide additional methods

The Set collection is not allowed to contain the same elements. If you try to add two same elements to the same Set collection, the adding operation will fail

Set judges whether two objects are the same instead of using the == operator, but according to the equals() method

One of the implementation classes of the Set interface: HashSet

HashSet is a typical implementation of the Set interface, and this implementation class is used most of the time when using the Set collection.

HashSet stores the elements in the set according to the Hash algorithm, so it has good access, search, and delete performance.

HashSet has the following characteristics:

  • Disorder: not equal to randomness. The stored data is not added in the order of the array index in the underlying array, but is determined according to the hash value of the data.
  • Non-repeatability: It is guaranteed that when the added element is judged according to equals(), it cannot return true, that is, only one of the same element can be added.
  • Collection elements can be null

HashSet sets the criteria for judging the equality of two elements: two objects are compared to be equal through the hashCode() method, and the return values ​​of the equals() method of the two objects are also equal.

For objects stored in the Set container, the corresponding class must override the equals() and hashCode(Object obj) methods to implement the object equality rule. That is: "Equal objects must have equal hash codes."

向HashSet中添加元素的过程:
    向HashSet中添加元素a,首先调用元素a所在类的hashCode()方法,计算元素a的哈希值,此哈希值接着通过某种算法计算出在		HashSet底层数组中的存放位置(即为:索引位置),判断数组此位置上是否已经有元素:
        如果此位置上没有其他元素,则元素a添加成功。 --->情况1
        如果此位置上其他有元素(或以链表形式存在的多个元素),则比较元素a与元素b的hash值:
            如果hash值不相同,则元素a添加成功。--->情况2
            如果hash值相同,进而需要调用元素a所在的类的equals()方法:
                equals()返回true,元素a添加失败
                equals()返回false,则元素a添加成功。--->情况2
	对于添加成功的情况2和情况3而言:元素a 与已经存在指定索引位置上数据以链表的方式存储。
    其中jdk7和jdk8中添加的位置还有所不同
    	jdk7:头插法
    	jdk8:尾插法

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-OUEcKkCz-1614868232498)(assets/image-20210212132446570.png)]

The basic principle of rewriting hashCode() method

  • When the program is running, multiple calls to the hashCode() method on the same object should return the same value.
  • When the equals() method of two objects compares and returns true, the return value of the hashCode() method of the two objects should also be equal.
  • Fields used for comparison in the equals() method of the object should be used to calculate the hashCode value.

Basic principles of overriding equals() method

  • When a class has its own unique concept of "logical equality", when rewriting equals(), always rewrite hashCode(). According to the equals method of a class (after rewriting), two completely different instances may be in logical The above are equal, but, according to the Object.hashCode() method, they are just two objects.
  • Therefore, it violates "equal objects must have equal hash codes".
  • Conclusion: When copying the equals method, it is generally necessary to copy the hashCode method at the same time. Usually the attributes of the objects involved in the calculation of hashCode should also participate in the calculation in equals().

Set implementation category two: LinkedHashSet

  • LinkedHashSet is a subclass of HashSet

  • LinkedHashSet determines the storage location of the element according to the hashCode value of the element, but it also uses a doubly linked list to maintain the order of the elements, which makes the elements appear to be stored in the order of insertion.

  • LinkedHashSet insert performance is slightly lower than HashSet, but
    it has good performance when iteratively accessing all elements in the Set .

  • LinkedHashSet does not allow duplicate collection elements.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-HwpTgeO9-1614868232504)(assets/image-20210212133058338.png)]

Set implementation category three: TreeSet

TreeSet is an implementation class of the SortedSet interface, and TreeSet can ensure that the collection elements are in a sorted state.

The bottom layer of TreeSet uses a red-black tree structure to store data. Features: orderly, query speed is faster than List

The new method is as follows:

  • Comparator comparator ()
  • Object first()
  • Object last()
  • Object lower(Object e)
  • Object higher(Object e)
  • SortedSet subSet(fromElement, toElement)
  • SortedSet headSet(toElement)
  • SortedSet tailSet(fromElement)

TreeSet has two sorting methods: natural sorting and custom sorting. By default, TreeSet uses natural sorting.

Sorting—Comparable

TreeSet will call the compareTo(Object obj) method of the collection elements to compare the size relationship between the elements, and then arrange the collection elements in ascending order (default)

If you try to add an object to the TreeSet, the object's class must implement the Comparable interface.

  • The class that implements Comparable must implement the compareTo(Object obj) method, and the two objects are compared in size by the return value of the compareTo(Object obj) method.

A typical implementation of Comparable:

  • BigDecimal, BigInteger, and all the packaging classes corresponding to the numeric type:
    compare them according to their corresponding numeric values
  • Character: Compare according to the unicode value of the character
  • Boolean: The wrapper class instance corresponding to true is greater than the wrapper class instance corresponding to false
  • String: Compare according to the unicode value of the characters in the string
  • Date, Time: The time and date behind are larger than the time and date in front

When adding elements to the TreeSet, only the first element does not need to be compared with the compareTo() method, and all elements added later will call the compareTo() method for comparison.

Because only two instances of the same class will be compared in size, the objects of the same class should be added to the TreeSet.

For the TreeSet collection, the only criterion for judging whether two objects are equal is: the two objects compare the return value through the compareTo(Object obj) method.

When you need to put an object in the TreeSet and rewrite the equals() method corresponding to the object, you should ensure that the method and the compareTo(Object obj) method have consistent results: if two objects are compared through the equals() method, it returns true , Then the comparison through the compareTo(Object obj) method should return 0.

Sorting—Comparator

The natural ordering of TreeSet requires the class to which the element belongs to implement the Comparable interface. If the class to which the element belongs does not implement the Comparable interface, or if you do not want to arrange the elements in ascending order (default) or want to sort them according to the size of other attributes, consider using custom sorting . Custom sorting is implemented through the Comparator interface. Need to rewrite compare(T o1,T o2) method.

Use the int compare(T o1,T o2) method to compare the sizes of o1 and o2: if the method returns a positive integer, it means o1 is greater than o2; if it returns 0, it means equal; it returns a negative integer, which means o1 is less than o2.

To implement custom sorting, an instance that implements the Comparator interface needs to be passed to the TreeSet constructor as a formal parameter.

At this point, you can still only add objects of the same type to the TreeSet. Otherwise, a ClassCastException exception occurs.

The criterion for judging the equality of two elements using custom sorting is: Comparator compares two elements and returns 0.

Guess you like

Origin blog.csdn.net/qq_44346427/article/details/110729387