Concept: compare two or more data items to determine whether they are equal, or to determine the size relationship between them and the order in which they are ranked.
1.Comparable Interface:
This interface forces the overall ordering of the objects for each class that implements it. This sort is called the natural ordering of the class, and the CompareTo method of the class is called its natural comparison method.
1 Public classComparabledemo {2 3 /**4 * @paramargs5 */6 Public Static voidMain (string[] args) {7 //TODO auto-generated Method Stub8Cat[] cats={NewCat ("Tom", 4),NewCat ("Jack", 3),NewCat ("Xiaohua", 5)};9 Arrays.sort (cats);Ten for(Cat cat:cats) { One System.out.println (cat); A } - } - the}
1 Public classCatImplementsComparable<cat> {2 PrivateString name;3 Private intAge ;4 5 PublicCat () {6 Super();7 //TODO auto-generated Constructor stub8 }9 PublicCat (String name,intAge ) {Ten Super(); One This. Name =name; A This. Age =Age ; - } - PublicString GetName () { the returnname; - } - Public voidsetName (String name) { - This. Name =name; + } - Public intGetage () { + returnAge ; A } at Public voidSetage (intAge ) { - This. Age =Age ; - } - @Override - PublicString toString () { - return"Cat [name=" + name + ", age=" + Age + "]"; in } - //object comparisons are achieved by this method to @Override + Public intcompareTo (Cat o) { - //TODO auto-generated Method Stub the if( This. Age <o.age) {//sort from small to large * return-1; $}Else if( This. Age >o.age) {Panax Notoginseng return1; -}Else{ the return0; + } A } the +}
2.Comparator interface: (Do not change the class, then write a comparison class)
Force a comparison of the overall ordering of an object collection.
1 Public classComparabledemo {2 3 /**4 * @paramargs5 */6 Public Static voidMain (string[] args) {7 //TODO auto-generated Method Stub8Dog[] dogs={NewDog ("Tom", 4),NewDog ("Jack", 3),NewDog ("Xiaohua", 5)};9Arrays.sort (Dogs,Newdogcomparator ());Ten for(Dog dog:dogs) { One System.out.println (dog); A } - } - the}
1 Public classDog {2 PrivateString name;3 Private intAge ;4 PublicDog () {5 Super();6 //TODO auto-generated Constructor stub7 }8 PublicDog (String name,intAge ) {9 Super();Ten This. Name =name; One This. Age =Age ; A } - PublicString GetName () { - returnname; the } - Public voidsetName (String name) { - This. Name =name; - } + Public intGetage () { - returnAge ; + } A Public voidSetage (intAge ) { at This. Age =Age ; - } - @Override - PublicString toString () { - return"Dog [name=" + name + ", age=" + Age + "]"; - } in}
1 ImportJava.util.Comparator;2 3 Public classDogcomparatorImplementsComparator<dog>{4 5 @Override6 Public intCompare (dog O1, dog O2) {7 //TODO auto-generated Method Stub8 if(O1.getage () <O2.getage ()) {9 return-1;Ten}Else if(O1.getage () >O2.getage ()) { One return1; A}Else{ - return0; - } the } - -}
Java object-oriented common class library api--object Comparator