Java's three major collections (two): Set

Set: Represents an unordered (stored in and taken out) non-repeatable collection, which can save null elements.
Under the interface: HashSet , TreeSet , LinkedHashSet

================================================================

HashSet : Based on HashMap, the bottom layer is key-value pair + linked list + red-black tree (after jdk1.8)
initial length: 16, load factor: 0.75

Mechanism for judging duplication: hashcode()—>equals()

  1. First determine the hashCode value of the element
  2. In the case of equal hashCode, continue to judge equals comparison, if they are equal, it is considered the same element

==============================================================

LinkedHashSet : is an ordered HashSet, a linked list is maintained on the basis of HashSet

==============================================================

TreeSet : Based on TreeMap, the bottom layer of TreeMap is based on red-black tree (it is a special binary tree with small left fork value and large right fork value, with self-balancing mechanism)

  1. Natural sorting: The element type must implement the Comparable interface, and the compareTo() method must be rewritten
    . Positive return value: ascending order
    Negative return value: descending order
    Return value 0: the same element will not be added

  2. Custom sorting: when creating a TreeSet object, pass in an implementation class of the Comparator interface, which must override the compare method
    . Positive return value: ascending order,
    negative return value: descending order,
    return value 0: the same element

Note:
1. When natural sorting and custom sorting are used at the same time, custom sorting has a higher priority.
2. Normally, natural sorting is used for default sorting , and custom sorting is used for special sorting.

==========================================================

Because Set is unordered and no subscript, there are only two traversal methods: foreach and one-way iterator

		//1、foreach
		for (Object object : hashSet) {
    
    
			System.out.println(object);
		}
		
		//单向迭代器
		Iterator iterator = hashSet.iterator();
		while (iterator.hasNext()) {
    
    
			Object object = (Object) iterator.next();
			System.out.println(object);
		}

Guess you like

Origin blog.csdn.net/ExceptionCoder/article/details/107631948