TreeSet and TreeMap sorting when comparing elements require element objects to implement comparable interfaces
There are two ways to compare elements in the collections sort method:
Element object implementation comparable interface
Entity class Dog
1 Public classDogImplementsCloneable,comparable<dog> {2 3 PrivateString name;4 PrivateString age;5 6 PublicString GetName () {7 returnname;8 }9 Public voidsetName (String name) {Ten This. Name =name; One } A PublicString getage () { - returnAge ; - } the Public voidsetage (String age) { - This. Age =Age ; - } - PublicDog (string name, String age) { + Super(); - This. Name =name; + This. Age =Age ; A } at PublicDog () { - Super(); - } - @Override - PublicString toString () { - return"Dog [name=" + name + ", age=" + Age + "]"; in } - to PublicObject Clone ()throwsclonenotsupportedexception { + - return Super. Clone (); the } * @Override $ Public intcompareTo (Dog o) {Panax Notoginseng - return This. GetName (). CompareTo (O.getname ()); the } +}
Test class
1 Public classTest {2 3 Public Static voidMain (string[] args) {4list<dog> list =NewArraylist<dog>();5Dog D1 =NewDog ("CAC", "11");6Dog D2 =NewDog ("BAC", "11");7Dog D3 =NewDog ("AAC", "11");8Dog D4 =NewDog ("EAC", "11");9 List.add (d1);Ten List.add (D2); One List.add (D3); A List.add (D4); - //Mycompare mc = new Mycompare (); - //Collections.sort (LIST,MC); the Collections.sort (list); - for(Dog dog:list) { - System.out.println (dog); - } + - } +}
Results:
Dog [NAME=AAC, age=11]
Dog [Name=bac, age=11]
Dog [NAME=CAC, age=11]
Dog [Name=eac, age=11]
Custom comparer, Collections.sort (List list,comparator<t> Compare), creating a comparator class implementation interface
1 Public classTest {2 3 Public Static voidMain (string[] args) {4list<dog> list =NewArraylist<dog>();5Dog D1 =NewDog ("CAC", "11");6Dog D2 =NewDog ("BAC", "11");7Dog D3 =NewDog ("AAC", "11");8Dog D4 =NewDog ("EAC", "11");9 List.add (d1);Ten List.add (D2); One List.add (D3); A List.add (D4); -Mycompare MC =NewMycompare (); - Collections.sort (LIST,MC); the for(Dog dog:list) { - System.out.println (dog); - } - + } - } + A classMycompareImplementsComparator<dog>{ at - @Override - Public intCompare (dog D1, dog D2) { -String S1 =d1.getname (); -String s2 =d2.getname (); - if(s1.equals (S2)) in return0; - Else { to returnS1.compareto (S2); + } - } the *}
Results:
Dog [NAME=AAC, age=11]
Dog [Name=bac, age=11]
Dog [NAME=CAC, age=11]
Dog [Name=eac, age=11]
How TreeMap and TreeSet compare elements when sorting, how the sort () method in the Collections tool class compares elements