"TreeSet Collection Usage Instance
"TreeSet collection of red and black tree storage and removal (figure)
"TreeSet" Add () method source code
- TreeSet Collection Usage Instances
Packagecn.itcast_05;ImportJava.util.TreeSet;/** TreeSet: Ability to sort elements according to a certain rule. * Sort in two ways * A: Natural sort * B: Comparator sort * * TreeSet set Features: Sort and unique * * by observing the Add () method of TreeSet, we know that we will eventually look at TreeMap's put () method. */ Public classTreesetdemo { Public Static voidMain (string[] args) {//To create a collection object//sort in natural ordertreeset<integer> ts =NewTreeset<integer>(); //Create elements and add//20,18,23,22,17,24,19,18,24Ts.add (20); Ts.add (18); Ts.add (23); Ts.add (22); Ts.add (17); Ts.add (24); Ts.add (19); Ts.add (18); Ts.add (24); //Traverse for(Integer i:ts) {System.out.println (i); } }}
- TreeSet collection of red and black tree storage and removal (figure)
- TreeSet the Add () method source code
Interface Collection{...}
Interface extends Collection{...}
Interface Navigablemap{...}
classTreeMapImplementsnavigablemap{Private Finalcomparator<?SuperK>Comparator; Publicv put (K key, V value) {Entry<K,V> t = root;//root element if(T = =NULL) {//at first, build the root element//TBD://5045147: (coll) Adding null to an empty TreeSet should//Throw NullPointerException// //Compare (key, key);//type CheckRoot =NewEntry<k,v> (key, value,NULL); Size= 1; Modcount++; return NULL; } intCMP; Entry<K,V>parent; //split comparator and comparable pathscomparator<?Superk> CPR = Comparator;//TreeMap created by the comparator? if(CPR! =NULL) { Do{Parent=T; CMP=Cpr.compare (key, T.key); if(CMP < 0) T=T.left; Else if(CMP > 0) T=T.right; Else returnT.setvalue (value); } while(t! =NULL); } Else { if(Key = =NULL) Throw NewNullPointerException (); Comparable<?Superk> k = (comparable<?Superk>) key;//Natural Sort, Integer implements comparable interface, and overrides the CompareTo () method Do{Parent=T; CMP=K.compareto (T.key); //less than left leaves, greater than leaves, equals when discarded if(CMP < 0) T=T.left; Else if(CMP > 0) T=T.right; Else returnT.setvalue (value); } while(t! =NULL); } Entry<K,V> e =NewEntry<k,v>(key, value, parent); if(CMP < 0) Parent.left=e; ElseParent.right=e; Fixafterinsertion (e); Size++; Modcount++; return NULL; }}
classTreeSetImplementsset{Private transientNavigablemap<e,object>m; TreeSet (Navigablemap<E,Object>m) { This. m =m; } PublicTreeSet () { This(NewTreemap<e,object>()); } Public BooleanAdd (e e) {returnM.put (e, PRESENT) = =NULL; }}
TreeSet collection of Add () method source code parsing (01.Integer natural sort)