Set
A collection that does not contain duplicate elements. To be exact, set does not contain e1 and e2 elements that meet e1.equals (e2), and can contain at most one null element;
This implementation is not synchronous. If multiple threads access a set at the same time and at least one thread modifies the set, it must maintain external synchronization, it is usually done by performing a synchronization operation on the object that encapsulates the set. If such an object does not exist, it will be: Collections. synchronizedSet ();
HashSet
The elements in the set are unordered and do not overlap. The data structure is a hash table;
Principle of ensuring element uniqueness: determines whether the HashCode value of the element is the same. If the HashCode value is the same, The equals method of the element will continue to be determined to be true; when an object is stored in a HashSet set, you cannot modify the fields of the object involved in calculating the hash value. If modified, internal leakage may occur;
TreeSet
You can sort the elements in the Set:
(1) make the elements have a comparison, and the elements need to implement the Comparable interface to overwrite the compareTo method. This method also becomes the natural order of the elements;
(2) The element itself does not have a comparison, or the comparison is not necessary. In this case, the set itself needs to have a comparison. When the set is initialized, the comparison method [defines the Comparator (Comparator <> Interface) and transmits it as a parameter to the constructor of the set]
The following two methods are required for the TreeSet interface:
Class Obj implements Comparable <Obj> {
Public int compareTo (Obj o ){
Return this. name. compareTo (o. name );
}}
Class Comptor implements Comparator <ComptorObj> {
@ Override
Public int compare (ComptorObj o1, ComptorObj o2 ){
Return o1.name. compareTo (o2.name );
}}