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 class'sNatural Sort, Class ofCompareTomethod is referred to as itsNatural Comparison Method。 The list of objects (and arrays) that implement this interface can beCollections.sort(andArrays.sort) for automatic sorting. 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. Consistent with equals means that for classesCof eachE1AndE2, when and only if(E1.compareto ((Object) e2) = = 0)Ande1.equals ((Object) E2)When you have the same Boolean value, the classCThe natural sort is calledconsistent 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);
}
}
Introduction to implementation and usage of comparable interface