1. What is the comparable interface?
This interface forces the overall ordering of the objects for each class that implements it. This sort is called the natural sort of the class, and the compareTo method of the class is called its natural comparison method . The list of objects (and arrays) that implement this interface can be automatically sorted by Collections.sort (and arrays.sort ). An object that implements this interface can be used as a key in an ordered map table or as an element in an ordered collection without specifying a comparer. It is strongly recommended (though not required) to make natural sorting consistent with equals. The so-called consistent with equals refers to each E1 and E2 of Class C , when and only if (E1.compareto (Object) e2 = = 0) with When E1.equals ((Object) E2) has the same Boolean value, the natural ordering of class C is called consistent with equals .
2. What method to implement
int CompareTo (T o) compares the order of this object with the specified object. If the object is less than, equal to, or greater than the specified object, it returns a negative integer, 0, or a positive integer, respectively.
It is highly recommended (X.compareto (y) ==0) = = (X.equals (y)) this practice, but not strictly required. In general, any implementation of comparable interfaces and classes that violate this condition should clearly state this fact. It is recommended that: "NOTE: This class has a natural sort that is inconsistent with equals. ”
Parameter: O-The object to compare. Return:
A negative integer, 0, or positive integer, depending on whether the object is less than, equal to, or greater than the specified object. Thrown:
ClassCastException-If the type of the specified object does not allow it to be compared with this object.
3. Example
import java.util.*;
- Public class employeesorttest {
- /**
- * @param args
- */
- Public Static void Main (string[] args) {
- TODO auto-generated Method Stub
- employee[] Staff = new employee[3];
- staff[0] = new Employee ("Harry Hacker", 35000);
- staff[1] = new Employee ("Carl Cracke", 75000);
- staff[2] = new Employee ("Tony Tester", 38000);
- Arrays.sort (staff); The Sort method enables you to sort an array of objects, but you must implement the comparable interface
- The/*comparable interface prototype is:
- * Public Interface Comparable<t>
- * {
- * int CompareTo (T other);//interface method automatically belongs to public method
- * }
- */
- for (Employee E:staff)
- System.out.println ("id=" +e.getid () + "Name=" +e.getname () +
- ". salary=" +e.getsalary ());
- }
- }
- /*
- * Because you want to implement the sort of the employee object, you implement the comparable interface in the Employee class,
- * I.E. to implement the Comepareto () method
- */
- class Employee implements comparable<employee>
- {
- Public Employee (String N, double s)
- {
- name = N;
- Salary = s;
- Random ID = new random ();
- id = id.nextint (10000000);
- }
- Public int getId ()
- {
- return ID;
- }
- Public String GetName ()
- {
- return name;
- }
- Public double Getsalary ()
- {
- return salary;
- }
- Public void raisesalary ( double bypercent)
- {
- double raise = Salary *bypercent/100;
- Salary+=raise;
- }
- Public int compareTo (Employee Other)
- {
- if (id<other.id)//What sort method is compared here to achieve is to follow this comparison of things from small to large arrangement
- return -1;
- if (id>other.id)
- return 1;
- return 0;
- }
- Private int ID;
- Private String name;
- Private Double salary;
- }
4. The difference from comparator
Comparator is located under Package Java.util, and comparable is under package Java.lang, the comparable interface embeds the comparison code in its own class, while the latter implements comparisons in a separate class. If the designer of the class does not implement the comparable interface without taking into account the compare problem, it can be sorted by comparator to implement the comparison algorithm, and to prepare for the use of different sorting criteria, such as ascending and descending.
Let's look at a comparator example:
Import Java.util.TreeSet;
Import Java.util.Comparator;
Class Numcomparator implements Comparator<nametag> {
public intCompare(NameTag Left,nametag right) {
Return (Left.getnumber ()-right.getnumber ());
}
}
public class Collectionnine {
public static void Main (String arg[]) {
New Collectionnine ();
}
Collectionnine () {
Numcomparator Comparator = new Numcomparator ();
treeset<nametag> set = new treeset<nametag> (comparator);
Set.add (New NameTag ("Agamemnon", 300));
Set.add (New NameTag ("Cato", 400));
Set.add (New NameTag ("Plato", 100));
Set.add (New NameTag ("Zeno", 200));
Set.add (New NameTag ("Archimedes", 500));
for (NameTag Tag:set)
SYSTEM.OUT.PRINTLN (tag);
}
}
Ext.: http://www.cnblogs.com/gnuhpc/archive/2012/12/17/2822251.html
Implementation and use of the comparable interface