1. What is the comparable interface?
This interface forcibly sorts the objects of each class. This sort is calledNatural sortingThe compareto method of the class is called itsNatural Comparison Method. Objects (and arrays) that implement this interface can be automatically sorted by collections. Sort (and arrays. Sort. Objects that implement this interface can be used as keys in an ordered ing table or elements in an ordered set without specifying a comparator. It is strongly recommended (though not required) to make the natural order consistent with equals. The same as equals means that for every E1 and E2 in Class C, when and only when (e1.compareto (object) E2) = 0) and e1.equals (object) E2) when the same Boolean value exists, the natural sorting of class C is calledSame as equals.
2. Implementation Method
Int compareto (t o) compares the order of the object with the specified object. If the object is smaller than, equal to, or greater than the specified object, a negative integer, zero, or positive integer is returned. We strongly recommend (X. compareto (y) = 0) = (X. Equals (y), but not strictly. In general, any class that implements the comparable interface and violates this condition should clearly point out this fact. We recommend that you elaborate: "NOTE: This class has a natural sorting that is inconsistent with equals ." Parameter: the object to be compared. Return Value:
Negative integer, zero, or positive integer, based on whether the object is smaller than, equal to, or greater than the specified object. Throw:
Classcastexception-if the specified object type cannot be compared with this object.
3. Instance
ImportJava. util .*;
PublicClassEmployeesorttest {
/**
* @ Param ARGs
*/
PublicStaticVoidMain (string [] ARGs ){
// Todo auto-generated method stub
Employee [] Staff =NewEmployee [3];
Staff [0] =NewEmployee ("Harry hacker", 35000 );
Staff [1] =NewEmployee ("Carl cracke", 75000 );
Staff [2] =NewEmployee ("Tony tester", 38000 );
Arrays. Sort (staff); // The sort method can sort object arrays, but the comparable interface must be implemented.
/* The comparable interface is prototype:
* Public interface comparable <t>
*{
* Int compareto (t other); // The method in the interface automatically belongs to the public method.
*}
*/
For(Employee E: Staff)
System. Out. println ("ID =" + E. GETID () + "name =" + E. getname () +
". Salary =" + E. getsalary ());
}
}
/*
* To sort the employee objects, you must implement the comparable interface in the employee class,
* That is, to implement the comepareto () method
*/
ClassEmployeeImplementsComparable <employee>
{
PublicEmployee (string N,DoubleS)
{
Name = N;
Salary = s;
Random id =NewRandom ();
Id = ID. nextint (10000000 );
}
PublicIntGETID ()
{
ReturnID;
}
PublicString getname ()
{
ReturnName;
}
PublicDoubleGetsalary ()
{
ReturnSalary;
}
PublicVoidRaisesalary (DoubleBypercent)
{
DoubleRaise = salary * bypercent/100;
Salary + = raise;
}
PublicIntCompareto (employee other)
{
If(ID <other. ID) // What sort method is compared here to implement the arrangement based on the comparison items from small to large
Return-1;
If(ID> other. ID)
Return1;
Return0;
}
PrivateIntID;
PrivateString name;
PrivateDoubleSalary;
}
4. Differences from Comparator
Comparator is located under the java. util package, while comparable is located under the java. lang package. The comparable interface embeds the comparison code into its own class, while the latter implements comparison in an independent class. If the class designer does not implement the comparable interface because of the Compare problem, you can use the comparator to sort the comparison algorithm and prepare for using different Sorting Standards. For example: in ascending or descending order.
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 );
}
}
Implementation and use of the comparable Interface