Java comparable interface object ordering

Source: Internet
Author: User
Tags comparable

Before writing an article is about comparator, then comparable must be taken out to do the analysis and contrast.

There are also a lot of articles on these two interfaces, and this article focuses on showing the description from the complete code example.

Ok

First, let's look at the code for the comparator interface here:

Public interface Comparable<t> {/** * Compares this object with the specified object for order.  Returns A * Negative integer, zero, or a positive integer as this object was less * than, equal to, or greater than     The specified object. * * <p>the implementor must ensure &LT;TT&GT;SGN (X.compareto (y)) = = *-SGN (Y.compareto (x)) </tt> for Al  L <tt>x</tt> <tt>y</tt>. (This * implies, <tt>x.compareto (y) </tt> must throw an exception iff * <tt>y.compareto (x) &lt     ;/tt> throws an exception.) * * <p>the implementor must also ensure that the relation is transitive: * <tt> (X.compareto (y) >0 &A     mp;& Y.compareto (z) >0) </tt> implies * <tt>x.compareto (z) >0</tt>. * * <p>finally, the implementor must ensure that <tt>x.compareto (y) ==0</tt> * implies that <t T&GT;SGN (X.compareto (z)) = = SGN (Y.compareto (z)) </tt>, foR * all <tt>z</tt>. * * <p>it is strongly recommended, but <i>not</i> strictly required that * <tt> (X.comparet  O (y) ==0) = = (X.equals (y)) </tt>. Generally speaking, any * class that implements the <tt>Comparable</tt> interface and violates * this  Condition should clearly indicate this fact.     The recommended * language is "Note:this class have a natural ordering that's * inconsistent with equals." * * <p>in The foregoing description, the notation * &LT;TT&GT;SGN (&LT;/TT&GT;&LT;I&GT;EXPRESSION&LT;/I&GT;&L t;tt>) </tt> designates the mathematical * <i>signum</i> function, which is defined to return one     of <tt>-1</tt>, * &LT;TT&GT;0&LT;/TT&GT;, or <tt>1</tt> according to whether the value of     * <i>expression</i> is negative, zero or positive.     * * @param o the object to be compared. * @return a negative integeR, Zero, or a positive integer as this object * are less than, equal to, or greater than the specified object. * * @throws NullPointerException If the specified object is null * @throws classcastexception if the Specifie     D object ' s type prevents it * from being compared to this object. */public int compareTo (T o);}
There's only one way, CompareTo (T O), nothing to say, simple ha

Now, give an example of implementing the interface: (Note that the annotations in it illustrate the purpose of the two interfaces)

Package Sometest;import Java.util.arraylist;import Java.util.collections;import Java.util.iterator;public class Comparableperson implements comparable<object> {     String firstname,lastname;      Boolean sex;     Integer age;    public Comparableperson ( String FirstName, String Lastname,boolean Sex, Integer age) {        this.firstname = firstname;        this.lastName  = lastname;        this. sex       = sex;        this.age        = age;    }    public String getfirstname () {           return firstName;        }               public String Getlastname () {          return lastName;        }         public Boolean getsex () {  & nbsp        return Sex;                         Public Integer Getage () {           return-age;          }       //For ease of input, override ToString ()    public String ToString ()         {           return firstName + "" + Lastname+ "" + (Sex.booleanvalue ()? " Male ":" female ") +" "+age;        }      //Definition comparison method     public int Compare (Object O1, Object O2) {         if (O1 instanceof String) {    & nbsp;     &NBSP;&NBsp;           return compareimp (String) O1, (string) O2);                   }else if ( O1 instanceof Integer) {                        return Compareimp ((integer) O1, (integer) O2);                   }else if ( O1 instanceof Boolean) {                      Return Compareimp ((Boolean) O1, (Boolean) O2);                 }else { // Expand the Compare function           System.err.println ("no suitable comparator found") as needed            return 1;         }       }      //Reload   public int Compareimp (string O1, String O2) {         string S1 = (string) O1;          string s2 = (string) O2;          int len1 = S1.length ();          int len2 = S2.length ();          int n = math.min (len1, len2);          char v1[] = S1.tochararray ();          char v2[] = S2.tochararray ();          int pos = 0;            while (n--! = 0) {            char c1 = V1[pos];            char c2 = V2[pos];            if (c1! = C2) {              return C1-C2;           }             pos++;         }          return Len1- Len2;       }      //overloaded  public int compareimp (integer o1, integer o2 ) {         int val1 = O1.intvalue ();           int val2 = O2.intvalue ();          return (Val1 < Val2 1: (Val1 = = val2? 0:1));         }    //overloaded public int Compareimp (Boolean O1, Boolean O2) {&nbs p;      return (o1.equals (O2) 0: (O1.booleanvalue () ==true?1:-1));      }         @Override     public int CompareTo ( Object o) {        comparableperson p = (comparableperson) o;          String firstname1 = P.getfirstname ();           String lastname1 = P.getlastname ();           Boolean sex1 = P.getsex ();           Integer age1 = P.getage ();                       int comparefirstname = Compare (This.firstname, firstname1);         int Comparelastname = Compare (This.lastname, lastname1);         int comparesex = Compare (this. Sex, sex1);            if (comparefirstname! = 0) {                return comparefirstname;            }            if (comparelastname!) = 0) {                return comparelastname;            }             if (comparesex! = 0) {                 return comparesex;           }             return Compare (This.age, age1);      }        public static void Main (string[] args) {   & nbsp;    comparableperson p1 = new Comparableperson ("Zangwu", "GG", false,27);         compaRableperson P2 = new Comparableperson ("Zhangsan", "GG", false,21);        int res = P1.compareto (p2);      /*returns a        * Negative integer, zero, or a positive integer as this object is less        * than, equ Al to, or greater than the specified object.        */         System.out.println (res);                /*         * Comparable interface and comparator interface are different, is the specific implementation method of different          * Specifically, in the implementation method, according to the comparison class of the field sort, by the programmer to write their own           * Comparable interface is characterized by the CompareTo (Object O) method, if you are the writer of the comparison class, you can implement      on the class to be sorted      * the interface; that's what's special about it.;         * in aIn some cases, this class you can only invoke, then you need to implement the comparator interface on your own class, with an int compare (object O1, Object O2)           * method to achieve a comparison of the class instance objects to be compared.          * That's what many people say comparable is an internal comparator, and comparator is an external comparator. */        arraylist<comparableperson> list = new ArrayList< Comparableperson> ();              // Add objects to ArrayList               List.add (new Comparableperson ("CCC", "AAA", true,20));               List.add (New Comparableperson ("AAA", "BBB", true,30));               List.add (New Comparableperson ("CCC", "AAA", false,10));               List.add (New Comparableperson ("CCC", "AAA", False, 40));                      //Printing the list's original sequence              System.out.println ("Before sorting:");            for (iterator< Comparableperson> iter = List.iterator (); Iter.hasnext ();) {                      Comparableperson person = (Comparableperson) iter.next ();                  System.out.println ("before sort=" +person);               }                        //Sort list                //This will be based on the "Comparableperson implementation of COmparable<object> interface "is sorted according to CompareTo (Object o)         Collections.sort (list);            for (int i = 0; i < List.size (); i++) {                if (i==0)                   System.out.println ("After sorting:");                  System.out.println ("after sort=" + list.get (i));              }      }}
Personal opinion, welcome to exchange.

Related Article

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.