Comparable and compareTo, compareto

Source: Internet
Author: User

Comparable and compareTo, compareto

Comparable

1. What is the Comparable interface?

This interface forcibly sorts the objects of each class. This sort is calledNatural sorting, ClassCompareToMethod is called itsNatural Comparison Method. You can useCollections. sort(AndArrays. sort. Objects that implement this interface can be used as keys in an ordered ing table or elements in an ordered set without specifying a comparator. It is strongly recommended (though not required) to make the natural order consistent with equals. The same as equals indicates thatCEveryE1AndE2For example(E1.compareTo (Object) e2) = 0)AndE1.equals (Object) e2)Class with the same Boolean ValueCThe natural sorting of is calledSame as equals.

2. Implementation Method

Int compareTo (T o) compares the order of the object with the specified object. If the object is smaller than, equal to, or greater than the specified object, a negative integer, zero, or positive integer is returned.
We strongly recommend (x. compareTo (y) = 0) = (x. equals (y), but not strictly. In general, any class that implements the Comparable interface and violates this condition should clearly point out this fact. We recommend that you elaborate: "NOTE: This class has a natural sorting that is inconsistent with equals ."
Parameter: the object to be compared. Return Value:
Negative integer, zero, or positive integer, based on whether the object is smaller than, equal to, or greater than the specified object. Throw:
ClassCastException-if the specified object type cannot be compared with this object.


The compareTo method must be rewritten to implement the Comparable interface. The Code is as follows:
1 package Demo4; 2 3 public class Person implements Comparable <Person> {4 private String name; 5 private int age; 6 private char sex; 7 8 public Person (String name, int age, char sex) {9 super (); 10 this. name = name; 11 this. age = age; 12 this. sex = sex; 13} 14 15/* (non-Javadoc) 16 * @ see java. lang. object # toString () 17 */18 @ Override19 public String toString () {20 return "Person [name =" + name + ", age =" + age + ", sex = "+ sex +"] "; 21} 22

// Rewrite different comparaTo methods when different sorting methods are used. at this time, corresponding to different data types 23 // public int compareTo (Person o) {24 // return this. the sex-o.sex; 25 26 // public int compareTo (Person o) {27 // return this. name. compareTo (o. name); 28 29 public int compareTo (Person o) {30 return this. age-o.age; 31} 33}

 

The main program is as follows:
1 package Demo4; 2 3 import java. util. treeSet; 4 5 public class Test {6 public static void main (String [] args) {7 TreeSet <Person> treeSet = new TreeSet <Person> (); 8 Person p1 = new Person ("Li Si", 34, 'male'); 9 Person p2 = new Person ("Zhang San", 23, 'female '); 10 Person p3 = new Person ("", 13, 'no'); 11 Person p4 = new Person ("", 25, '2'); 12 treeSet. add (p1); 13 treeSet. add (p2); 14 treeSet. add (p3); 15 treeSet. add (p4); 16 17 for (Person person: treeSet) {18 System. out. println (person); 19} 20} 21}

The displayed results are sorted alphabetically by the selected sorting method.

 

 

Comparator

Like Comparable, Comparator is an interface that meets certain requirements. difference: Comparable can only make the class where the stored object is located Comparable. When the class has multiple attributes and needs to be sorted by different attributes, Comparable cannot be completed. comparable needs to override the comparaTo method.

The Comparator sorts different attributes of a class according to requirements and needs to override the compare method.

  

Comparator instance

1 // create a new class with different attributes: 2 package Demo5; 3 4 public class Person {5 private String name; 6 private int age; 7 private char sex; 8 public Person (String name, int age, char sex) {9 super (); 10 this. name = name; 11 this. age = age; 12 this. sex = sex; 13} 14 public Person () {15 super (); 16} 17/** 18 * @ return name 19 */20 public String getName () {21 return name; 22} 23/** 24 * @ param nane name 25 */26 public void setName (String name) {27 this. name = name; 28} 29/** 30 * @ return age 31 */32 public int getAge () {33 return age; 34} 35/** 36 * @ param age the age 37 */38 public void setAge (int age) {39 this. age = age; 40} 41/** 42 * @ return sex 43 */44 public char getSex () {45 return sex; 46} 47/** 48 * @ param sex the sex 49 */50 public void setSex (char sex) {51 this. sex = sex; 52} 53/* (non-Javadoc) 54 * @ see java. lang. object # toString () 55 */56 @ Override 57 public String toString () {58 return "Person [name =" + name + ", age =" + age + ", sex = "+ sex +"] "; 59}; 60 61} 62 63 64 // create a comparator 65 package Demo5; 66 67 import java. util. comparator; 68 69 public class AgeComparator implements Comparator <Person> {70 71 @ Override 72 public int compare (Person o1, Person o2) {73 // int type is converted to an Integer class here. comparaTo can be used for comparison. if not converted, A = is used to judge 74 if (new Integer (o1.getAge ()). compareTo (new Integer (o2.getAge () = 0) {75 if (o1.getName (). compareTo (o2.getName () = 0) {76 if (o1.getSex () = o2.getSex () {77 return 0; 78} else {79 return o1.getSex () -o2.getSex (); 80} 81 82} else {83 return o1.getName (). compareTo (o2.getName (); 84} 85 86} 87 return o1.getAge ()-o2.getAge (); 88 89} 90} 91 92 // main function 93 package Demo5; 94 95 import java. util. treeSet; 96 97 public class Test {98 public static void main (String [] args) {99 100 // 1 NameComparator namecomparator = new NameComparator (); 101 // TreeSet <Person> set = new TreeSet <Person> (new NameComparator (); 102 // select the comparator to use, the anonymous internal class can simplify code 103 TreeSet <Person> set = new TreeSet <Person> (new AgeComparator (); 104 Person p1 = new Person ("Xiaohong", 23, 'No'); 105 Person p2 = new Person ("James", 19, 'female "); 106 Person p3 = new Person (" Xiaohua ", 16, 'male'); 107 Person p4 = new Person ("watch", 14, 'female "); 108 Person p5 = new Person (" ", 24, 'non'); 109 set. add (p1); 110 set. add (p2); 111 set. add (p3); 112 set. add (p4); 113 set. add (p5); 114 115 for (Person person: set) {116 System. out. println (person); 117} 118} 119}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.