Implementation and use of the comparable interface

Source: Internet
Author: User
Tags comparable

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

  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 enables you to sort an array of objects, but you must implement the comparable interface
  12. The/*comparable interface prototype is:
  13. * Public Interface Comparable<t>
  14. * {
  15. * int CompareTo (T other);//interface method automatically belongs to 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. * Because you want to implement the sort of the employee object, you implement the comparable interface in the Employee class,
  25. * I.E. 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 sort method is compared here to achieve is to follow this comparison of things from small to large arrangement
  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. 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

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.