Sorting comparable interfaces and comparator interfaces in Java

Source: Internet
Author: User

In order for a generic class to be sorted, the comparable interface must be implemented and the CompareTo () method rewritten.

package test;public class field implements comparable<field> {     private String name;    private int age;     public field ()  {    }    public field (String  name, int age)  {        this.name =  name;        this.age = age;    }     public string getname ()  {         Return name;    }    public void setname (String  Name)  {        this.name = name;     }    public int getage ()  {         return age; &nbSp;  }    public void setage (int age)  {         this.age = age;    }


@Override     public int compareto (Field o)  {         //  first Sort by age         if  (this.age  > o.getage ())  {            return   (This.age - o.getage ());        }         if  (This.age < o.getage ())  {             return  (This.age - o.getage ());         }        //  Sort by name          if  (This.name.compareTo (O.getname ())  > 0)  {             return 1;         }        if  (This.name.compareTo (O.getname ())  < 0)  {             return -1;         }        return 0;     }}package test;
Import java.util.arraylist;import java.util.collections;import java.util.list;public class  test2 {    public static void main (String[] args)  {         field f1 = new field ("Tony",  11);         field f2 = new field ("Jack",  11);         field f3 = new field ("Tom",  11);         field f4 = new field ("Jason",  44);         List<Field> list = new ArrayList< Field> ();         list.add (F1);         list.add (F3);         list.add (f4);         list.aDD (F2);         collections.sort (list);         for  (field o : list)  {             system.out.println (O.getage ()  +  "--"  + o.getname ());         }    }}



Comparator  

package com.tianjf;            import  java.util.arrays;      import java.util.comparator;             public class MyComparator implements  comparator<object> {                  @Override           public int  Compare (OBJECT&NBSP;O1,&NBSP;OBJECT&NBSP;O2)  {               return toint (O1)  - toint (O2);           }                 private int toint (Object o)  {               string str =  (String)  o;               str = str.replaceall ("One",  "1");               str = str.replaceall ("Two",  "2");               str = str.replaceall (" Three ", " 3 ");              return  Integer.parseint (str);           }

/**

* Test method

*/

public static void main (String[] args)  {               String[] array =  new string[] {  "One",  "three",  "two"  };               arrays.sort (Array, new mycomparator ());               for  (int i = 0; i  < array.length; i++)  {                   system.out.println (Array[i]);               }          }       } 


I believe that after reading the code should understand some of it, and now simply say the difference between the comparable interface and the comparator interface (purely personal idea). I think the biggest function of the comparable interface is to define a custom class's comparison rules, because the CompareTo method has only one parameter and the other parameter is this, which is the class itself, so we can think of it as defining a comparison rule within the class. The equivalent of a Java developer writing a string class should allow it to implement the comparable interface. However, the Compare method has two parameters, which can be of any type, either a string type that has already been defined, or a custom type. If it is a type that has already been defined, the Compare method can redefine its rules, and if it is a custom type, you can define a new rule.

Summarize:

Comparable is to support self-comparison, while the latter is to support external comparisons;

comparable& Comparator are used to implement sorting in the collection, except that comparable is the sort of method implementation defined within the collection, Comparator is the sort implemented outside the collection, so, if you want to implement sorting, It is necessary to define the method of the comparator interface outside the collection compare () or the method CompareTo () that implements the comparable interface within the collection.

Comparable is an interface that the object itself has implemented to support self-comparison (such as String integer itself can do the comparison size operation)

While comparator is a dedicated comparator, you can write a comparator to compare the size of two objects when the object does not support self-comparison or the self-comparison function does not meet your requirements.

This means that when you need to compare an array or set of a custom class, you can implement the comparable interface, and when you need to compare an array or set of an existing class, you must implement the comparator interface. In addition, these two interfaces support generics, so we should define the comparison type while implementing the interface.


This article is from the "BREEZEWINDLW" blog, make sure to keep this source http://breezewindlw.blog.51cto.com/6504579/1616530

Sorting comparable interfaces and comparator interfaces in Java

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.