Presondemo
PackageCn.stat.p5.person.demo; Public classPresondemoImplementsComparable {PrivateString name; Private intAge ; /** * @paramargs*/ PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } Public voidOutprint () {System.out.println ( This. age+ ".." + This. Name); } PublicPresondemo (String name,intAge ) { This. Name =name; This. Age =Age ; } //TreeSet (); For empty, real-class internal comparators@Override Public intcompareTo (Object o) {//TODO auto-generated Method StubPresondemo p=(Presondemo) o; if(p.age< This. Age)return1; if(p.age> This. Age)return-1; return0; }}
Comparator Compartorbyname
/*** Return ORDER by name*/ PackageCn.stat.p6.arraylist.demo;ImportJava.util.Comparator;ImportCn.stat.p5.person.demo.PresonDemo;/** * @authorAdministrator **/ Public classCompartorbynameImplementsComparator {/*(non-javadoc) * @see java.util.comparator#compare (java.lang.Object, Java.lang.Object)*/@Override Public intCompare (Object O1, Object O2) {//TODO auto-generated Method StubPresondemo p1=(Presondemo) O1; Presondemo P2=(Presondemo) O2; inttemp=p1.getname (). CompareTo (P2.getname ()); returnTemp==0?p1.getage ()-p2.getage (): temp; }}
Treesetdemo
PackageCn.stat.p6.arraylist.demo;ImportCn.stat.p5.person.demo.PresonDemo;ImportJava.util.Iterator;ImportJava.util.TreeSet;Importjava.util.ArrayList; Public classTreesetdemo { Public Static voidMain (string[] args) {TreeSet ts=NewTreeSet (Newcompartorbyname ()); Comparator Ts.add (NewPresondemo ("List1", 2)); Ts.add (NewPresondemo ("List9", 2)); Ts.add (NewPresondemo ("List7", 2)); Ts.add (NewPresondemo ("List4", 2)); Ts.add (NewPresondemo ("List5", 2)); Iterator<PresonDemo> it=Ts.iterator (); while(It.hasnext ()) {Presondemo P=(Presondemo) it.next (); System.out.println (P.getname ()+" "+p.getage ()); } }}
Java Comparator Comparator use