Implementation and use of the comparable Interface

Source: Internet
Author: User

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 .*;

  1. PublicClassEmployeesorttest {


  2. /**

  3. * @ Param ARGs

  4. */

  5. PublicStaticVoidMain (string [] ARGs ){

  6. // Todo auto-generated method stub

  7. Employee [] Staff =NewEmployee [3];

  8. Staff [0] =NewEmployee ("Harry hacker", 35000 );

  9. Staff [1] =NewEmployee ("Carl cracke", 75000 );

  10. Staff [2] =NewEmployee ("Tony tester", 38000 );


  11. Arrays. Sort (staff); // The sort method can sort object arrays, but the comparable interface must be implemented.

  12. /* The comparable interface is prototype:

  13. * Public interface comparable <t>

  14. *{

  15. * Int compareto (t other); // The method in the interface automatically belongs to the public method.

  16. *}

  17. */

  18. For(Employee E: Staff)

  19. System. Out. println ("ID =" + E. GETID () + "name =" + E. getname () +

  20. ". Salary =" + E. getsalary ());

  21. }


  22. }

  23. /*

  24. * To sort the employee objects, you must implement the comparable interface in the employee class,

  25. * That is, to implement the comepareto () method

  26. */

  27. ClassEmployeeImplementsComparable <employee>

  28. {

  29. PublicEmployee (string N,DoubleS)

  30. {

  31. Name = N;

  32. Salary = s;

  33. Random id =NewRandom ();

  34. Id = ID. nextint (10000000 );

  35. }

  36. PublicIntGETID ()

  37. {

  38. ReturnID;

  39. }

  40. PublicString getname ()

  41. {

  42. ReturnName;

  43. }


  44. PublicDoubleGetsalary ()

  45. {

  46. ReturnSalary;

  47. }


  48. PublicVoidRaisesalary (DoubleBypercent)

  49. {

  50. DoubleRaise = salary * bypercent/100;

  51. Salary + = raise;

  52. }


  53. PublicIntCompareto (employee other)

  54. {

  55. If(ID <other. ID) // What sort method is compared here to implement the arrangement based on the comparison items from small to large

  56. Return-1;

  57. If(ID> other. ID)

  58. Return1;

  59. Return0;

  60. }

  61. PrivateIntID;

  62. PrivateString name;

  63. PrivateDoubleSalary;

  64. }

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

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.