concept
First, let's take a look at the Set collection.
(01) Set is an interface inherited from Collection. It is a collection that does not allow duplicate elements.
(02) AbstractSet is an abstract class, which inherits from AbstractCollection. AbstractCollection implements most functions in Set, providing convenience for Set implementation classes.
(03) HastSet and TreeSet are two implementation classes of Set.
HashSet relies on HashMap, which is actually implemented through HashMap. The elements in the HashSet are out of order.
TreeSet relies on TreeMap, which is actually implemented through TreeMap. The elements in TreeSet are ordered.
eg:
Let’s take a look at the utilization of set collections by traversing violations:
package com.sort; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * A collection that does not contain duplicate elements. More specifically, set does not contain elements that satisfy e1.equals(e2), e1 and e2, * @author Owner * */ public class SetTest2 { public static void main(String[] args) { Set<String> set = new HashSet<String>(); set.add("a"); set.add("b"); set.add("c"); set.add("d"); set.add("e"); set.add("e"); set.add("e"); //Double data cannot be put in /** * Traversal method 1, iterative traversal*/ for(Iterator<String> iterator = set.iterator();iterator.hasNext();){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("************************"); /** * for enhanced loop traversal*/ for(String value : set){ System.out.print(value+" "); } } } Note: The String type is placed in the Set collection. If we put a class instance that we define, such as Person class instance, we have to re-hashcode and equal methods ourselves and rewrite them with our own key fields, because when using HashSet, the hashCode() method will be called to determine whether the hash code value of the object that has been stored in the collection is consistent with the hash code value of the added object; if it is inconsistent, add it directly; if it is consistent, compare the equals method. If the equals method returns true, it means that the object has been added, and no new objects will be added, otherwise it will be added.