Implementation and use of the Comparable interface

1. What is the Comparable interface

  This interface imposes its object to realize a total ordering of each class. This ordering is called class natural ordering  , class  compareTo  method is referred to as its natural comparison method  . Implementation of this interface object list (and arrays) may be  the Collections.sort  (and  Arrays.sort  automatically sort). Object implementing this interface can be used as key elements of an ordered set of ordered or in the mapping table, without specifying the comparator. Strongly recommended (though not required) that natural orderings be consistent with equals. The so-called uniform and equals refers to the class  of each of a  e1  and  e2  for, if and only if  (e1.compareTo ((Object) e2)  == 0) and e1.equals ((Object) e2)  with the same Boolean value, class  natural ordering it is called consistent with the equals  .

 

2. To achieve what method

int compareTo (T o) 
Compare this object with the specified object. If the object is less than, equal to or greater than the specified object, a negative integer, zero or a positive integer. 
Highly recommended (x.compareTo (y) == 0) == (x.equals (y)) such practices, but not strictly required to do so. In general, any implement the Comparable interface and violates this condition classes should clearly indicate this fact.
The recommended language is: "Note: This class has a natural ordering is inconsistent with equals."

Parameters: 
       O - object to compare. 
return:
        Negative integer, zero or a positive integer, as this object is less than, equal to, or greater than the specified object. 
Throws:
        ClassCastException - if the specified object's type prevents it from being compared to this object. 

3. Examples

 1 import java.util.*;  
 2 
 3 public class EmployeeSortTest {  
 4 /**
 5      * @param args
 6      */
 7 public static void main(String[] args) {  
 8 // TODO Auto-generated method stub
 9         Employee[] staff =  new Employee[ 3 ];  
10         staff[ 0 ] =  new Employee( "harry Hacker" , 35000 );  
11         staff[ 1 ] =  new Employee( "carl cracke" , 75000);  
 12 is          Staff [2] =   new new the Employee ( "Tony Tester", 38000 );  
 13 is          Arrays.sort (Staff); // Sort sorting methods may be implemented for an array of objects, but must implement Comparable interface 
14  / * Comparable interface prototype :
 15                              * public interface the Comparable <T>
 16                              * {
 . 17                              * int the compareTo (T OTHER); // interface method automatically belong to public method
 18 is                              *}
 . 19                              * / 
20 is  for (the Employee E: Staff)  
 21 is              the System.out. println ( "id =" + e.getId  
 () + "name =" + e.getName () +22 is "a .salary =" + e.getSalary ());  
 23 is      }  
 24  }  
 25  / * 
26 is  * sort to achieve because Employee object, so in order to achieve the Employee class Comparable interface,
 27  * is to achieve comepareTo ( ) method
 28  * / 
29  class the Employee   the implements the Comparable <the Employee>  
 30  {  
 31 is  public the Employee (n-String, Double S)  
 32      {  
 33 is          name = n-;  
 34 is          the salary = S;  
 35          the Random ID =   new new the Random ();  
 36         id = ID.nextInt( 10000000 );  
37     }  
38 public int getId()  
39     {  
40 return id;  
41     }  
42 public String getName()  
43     {  
44 return name;  
45     }  
46 public double getSalary()  
47     {  
48 return salary;  
49     }  
50 public void raiseSalary( double byPercent)  
51     {  
 52 is  Double The raise the salary = byPercent * / 100 ;  
 53 is          the salary + = The raise;  
 54 is      }  
 55  public  int the compareTo (the Employee OTHER)  
 56 is      {  
 57 is  IF (ID <other.id) // this comparison what sort method is implemented in accordance with what this comparison in ascending order 
58  return -. 1 ;  
 59  IF (ID> other.id)  
 60  return . 1 ;  
 61 is  return 0 ;  
 62 is      }  
 63 is  Private  int ID;  
64 private String name;  
65 private double salary;  
66 }

 

4. The difference with the Comparator 
Comparator Classes in java.util located in the package, the package java.lang located at Comparable,
Comparable comparison code into its own interface class, which implements the comparison in a separate class.
If the class of the designers did not take into account the problem of Compare and did not implement the Comparable interface,
can be achieved by comparison algorithm to sort Comparator, and in order to use different sorting criteria to prepare, for example: ascending, descending.

We look at an example of a Comparator:
 1 import java.util.TreeSet;
 2 import java.util.Comparator;
 3 class NumComparator implements Comparator<NameTag> {
 4     public int compare (NameTag left,NameTag right) {
 5         return(left.getNumber() - right.getNumber());
 6     }
 7 }
 8 public class CollectionNine {
 9     public static void main(String arg[]) {
10         new CollectionNine();
11     }
12     CollectionNine() {
13         NumComparator comparator = new NumComparator();
14         TreeSet<NameTag> set = new TreeSet<NameTag>(comparator);
15         set.add(new NameTag("Agamemnon",300));
16         set.add(new NameTag("Cato",400));
17         set.add(new NameTag("Plato",100));
18         set.add(new NameTag("Zeno",200));
19         set.add(new NameTag("Archimedes",500));
20         for(NameTag tag : set)
21             System.out.println(tag);
22     }
23 }
 

 



 

Guess you like

Origin www.cnblogs.com/wl-centrinc/p/11872758.html