Only the use of methods, non-source analysis.
1 Public classTest {2 3 Public Static voidMain (string[] args) {4Treeset<string> treeset=NewTreeset<>();5Treeset.add ("Se");6Treeset.add ("Ald");7Treeset.add ("Boo");8Treeset.add ("CC");9Iterator<string> iterator=treeset.iterator ();Ten while(Iterator.hasnext ()) { OneString string =(String) Iterator.next (); A System.out.println (string); - } - } the -}
Output:
Ald
Boo
Cc
Se
When using the TreeSet collection, the element must implement the comparable interface.
1 Public classPersonImplementsComparable<person> {2 PrivateString name;3 Private intAge ;4 5 PublicPerson () {6 //TODO auto-generated Constructor stub7 }8 9 PublicPerson (String name,intAge ) {Ten This. Name =name; One This. Age =Age ; A } - - PublicString GetName () { the returnname; - } - - Public voidsetName (String name) { + This. Name =name; - } + A Public intGetage () { at returnAge ; - } - - Public voidSetage (intAge ) { - This. Age =Age ; - } in - @Override to PublicString toString () { + //TODO auto-generated Method Stub - return"Name:" + getName () + "Age:" +getage (); the } * $ /**Panax Notoginseng * Ascending order - */ the @Override + Public intcompareTo (person person) { A //TODO auto-generated Method Stub the if( This. Getage () >Person.getage ()) { + return1; -}Else if( This. getage () = =Person.getage ()) { $ return0; $}Else { - return-1; - } the } - Wuyi}
Test class:
1 Public classTest {2 3 Public Static voidMain (string[] args) {4 //TODO auto-generated Method Stub5Treeset<person> Tset =NewTreeset<>();6Tset.add (NewPerson ("Shldom", 23));7Tset.add (NewPerson ("Tom", 12));8Tset.add (NewPerson ("Woa", 45));9Tset.add (NewPerson ("Moe", 87));TenIterator<person> iterator=tset.iterator (); One while(Iterator.hasnext ()) { A System.out.println (Iterator.next ()); - } - } the -}
Output Result:
Name:tom Age:12
Name:shldom age:23
Name:woa age:45
Name:moe age:87
TreeSet Simple to use