/*** Student class *@authorAdministrator **/ Public classStudent {PrivateString Sno; PrivateString sname; PrivateInteger score; PublicStudent (String sno, String sname, Integer score) {Super(); This. Sno =Sno; This. sname =sname; This. score =score; } PublicString Getsno () {returnSno; } Public voidSetsno (String Sno) { This. Sno =Sno; } PublicString Getsname () {returnsname; } Public voidsetsname (String sname) { This. sname =sname; } PublicInteger Getscore () {returnscore; } Public voidSetScore (Integer score) { This. score =score; } ImportJava.util.Comparator;
/*** Compare algorithm classes, comparators *@authorAdministrator **/ Public classmycmpImplementsComparator<student>{@Override Public intCompare (Student O1, Student O2) {//TODO auto-generated Method Stub if(O1.getscore () >O2.getscore ()) { return1; } Else if(O1.getscore () <O2.getscore ()) {
return-1;
Else { return 0; } } Package TR
Importjava.util.treeset;//Test Class Public classTest { Public Static voidMain (string[] args) {TreeSet<Student> set =NewTreeset<student> (Newmycmp ()); Student S1=NewStudent ("1001", "Chen", 67); Student S2=NewStudent ("1001", "Zhang", 17); Student S4=NewStudent ("1003", "Zeng", 47); Student S5=NewStudent ("1004", "Wang", 87); Student S6=NewStudent ("1005", "Chao", 67); Student S3=NewStudent ("1002", "Zhou", 62); Set.add (S1); Set.add (S2); Set.add (S3); Set.add (S4); Set.add (S5); Set.add (S6); for(Java.util.iterator<student> it=set.iterator (); It.hasnext ();) {Student s=It.next (); System.out.println (S.getsno ()+ "," +s.getsname () + "," +S.getscore ()); } }}
/*** Student class *@authorAdministrator **/ Public classStudent1ImplementsComparable<student1>{ PrivateString Sno; PrivateString sname; PrivateInteger score; PublicStudent1 (String sno, String sname, Integer score) {Super(); This. Sno =Sno; This. sname =sname; This. score =score; } PublicString Getsno () {returnSno; } Public voidSetsno (String Sno) { This. Sno =Sno; } PublicString Getsname () {returnsname; } Public voidsetsname (String sname) { This. sname =sname; } PublicInteger Getscore () {returnscore; } Public voidSetScore (Integer score) { This. score =score; } //Custom Collation@Override Public intCompareTo (Student1 s) {if( This. Getscore () >S.getscore ()) { return1; } Else if( This. Getscore () <S.getscore ()) { return-1; } Else { return0; } }}
Comparator and comparable, custom sort and class comparer, TreeSet object sorting