TreeSet: Ability to sort elements according to a certain rule.
There are two ways of sorting
A: Natural Sort
B: Comparator sort
Features of the TreeSet collection: sort and unique
1 Public classTreesetdemo {2 Public Static voidMain (string[] args) {3 //To create a collection object4 //sort in natural order5treeset<integer> ts =NewTreeset<integer>();6 7 //Create elements and add8 //20,18,23,22,17,24,19,18,249Ts.add (20);TenTs.add (18); OneTs.add (23); ATs.add (22); -Ts.add (17); -Ts.add (24); theTs.add (19); -Ts.add (18); -Ts.add (24); - + //Traverse - for(Integer i:ts) { + System.out.println (i); A } at } -}
By observing the Add () method of TreeSet, we know that we will eventually look at the put () method of TreeMap.
Source code for the Add () method of the Tressset collection:
1 InterfaceCollection {...}2 3 InterfaceSetextendsCollection {...}4 5 InterfaceNavigablemap {6 7 }8 9 classTreeMapImplementsNavigablemap {Ten Publicv put (K key, V value) { OneEntry<k,v> T =Root; A if(T = =NULL) { -Compare (key, key);//type (and possibly null) check - theRoot =NewEntry<> (key, value,NULL); -Size = 1; -modcount++; - return NULL; + } - intCMP; +Entry<k,v>parent; A //split comparator and comparable paths atcomparator<?Superk> CPR =Comparator; - if(CPR! =NULL) { - Do { -Parent =T; -CMP =Cpr.compare (key, T.key); - if(CMP < 0) int =T.left; - Else if(CMP > 0) tot =T.right; + Else - returnT.setvalue (value); the} while(t! =NULL); * } $ Else {Panax Notoginseng if(Key = =NULL) - Throw Newnullpointerexception (); thecomparable<?Superk> k = (comparable<?SuperK>) key; + Do { AParent =T; theCMP =K.compareto (t.key); + if(CMP < 0) -t =T.left; $ Else if(CMP > 0) $t =T.right; - Else - returnT.setvalue (value); the} while(t! =NULL); - }WuyiEntry<k,v> e =NewEntry<>(key, value, parent); the if(CMP < 0) -Parent.left =e; Wu Else -Parent.right =e; About fixafterinsertion (e); $size++; -modcount++; - return NULL; - } A } + the classTreeSetImplementsSet { - Private transientNavigablemap<e,object>m; $ the PublicTreeSet () { the This(NewTreemap<e,object>()); the } the - Public BooleanAdd (e e) { in returnM.put (e, PRESENT) = =NULL; the } the } About the The real comparison is dependent on the CompareTo () method of the element, and this method is defined in the comparable. the So, if you want to rewrite the method, you must first comparable the interface. This interface represents a natural sort. the +
TreeSet storage elements Natural ordering and unique plots
Java 17-6 TreeSet Collection and its Add () method source code parsing