Comparable interface implementation and usage introduction, comparable Interface

Source: Internet
Author: User

Comparable interface implementation and usage introduction, comparable Interface

1. What is the Comparable interface?

This interface forcibly sorts the objects of each class. This sort is called the natural sorting of the classCompareToMethod is called its natural comparison method. You can useCollections. sort(AndArrays. 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 indicates thatCEveryE1AndE2For example(E1.compareTo (Object) e2) = 0)AndE1.equals (Object) e2)Class with the same Boolean ValueCThe natural sorting of is called the same 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

Import java. util .*;

  1. Public class EmployeeSortTest {
  2. /**
  3. * @ Param args
  4. */
  5. Public static void main (String [] args ){
  6. // TODO Auto-generated method stub
  7. Employee [] staff = new Employee [3];
  8. Staff [0] = new Employee ("harry Hacker", 35000 );
  9. Staff [1] = new Employee ("carl cracke", 75000 );
  10. Staff [2] = new Employee ("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. Class Employee implements Comparable <Employee>
  28. {
  29. Public Employee (String n, double s)
  30. {
  31. Name = n;
  32. Salary = s;
  33. Random ID = new Random ();
  34. Id = ID. nextInt (10000000 );
  35. }
  36. Public int getId ()
  37. {
  38. Return id;
  39. }
  40. Public String getName ()
  41. {
  42. Return name;
  43. }
  44. Public double getSalary ()
  45. {
  46. Return salary;
  47. }
  48. Public void raiseSalary (double byPercent)
  49. {
  50. Double raise = salary * byPercent/100;
  51. Salary + = raise;
  52. }
  53. Public int compareTo (Employee other)
  54. {
  55. If (id <other. id) // What is the sort method compared here? The sort method is implemented according to the comparison items in ascending order.
  56. Return-1;
  57. If (id> other. id)
  58. Return 1;
  59. Return 0;
  60. }
  61. Private int id;
  62. Private String name;
  63. Private double salary;
  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 int compare (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 );
}
}

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.