Sort objects, CompareTo

Source: Internet
Author: User
Tags comparable

A first example

Java code
  1. /* To compare, let your class implement the comparable interface and rewrite it in the sort order you want CompareTo
  2. *map just provides a sort of key, but when we need to sort the values, we provide our own comparators. Here we just modeled the map but didn't actually use the map.
  3. */
  4. Import Java.util.Iterator;
  5. Import Java.util.Set;
  6. Import Java.util.TreeSet;
  7. Public class Sortbyvalue {
  8. public static void Main (string[] args) {
  9. set<pair> set = new treeset<pair> ();
  10. Set.add (new Pair ("Me", "1000"));
  11. Set.add (new Pair ("and", "4000"));
  12. Set.add (new Pair ("You", "3000"));
  13. Set.add (new Pair ("Food", "10000"));
  14. Set.add (new Pair ("Hungry", "5000"));
  15. Set.add (new Pair ("later", "6000"));
  16. Set.add (new Pair ("Myself", "1000"));
  17. For (iterator<pair> i = Set.iterator (); I.hasnext ();)
  18. //I like this for statement
  19. System.out.println (I.next ());
  20. }
  21. }
  22. Class Pair implements Comparable<object> {
  23. Private final String name;
  24. private final int number;
  25. Public Pair (String name, int number) {
  26. this.name = name;
  27. this.number = number;
  28. }
  29. Public Pair (string name, string number) throws NumberFormatException {
  30. this.name = name;
  31. This.number = integer.parseint (number);
  32. }
  33. public int compareTo (Object o) {
  34. if (o instanceof Pair) {
  35. //INT cmp = double.compare (number, (Pair) O). number);
  36. INT cmp = number-((Pair) O). number;
  37. if (cmp! = 0) {//number is the first to compare, it is equivalent to comparing value first. If the same re-compare key
  38. return CMP;
  39. }
  40. return Name.compareto ((Pair) O). Name);
  41. }
  42. throw New ClassCastException ("Cannot compare Pair with"
  43. + O.getclass (). GetName ());
  44. }
  45. Public String toString () {
  46. return name + ' + number;
  47. }
  48. }
  49. Output Result:
  50. Me
  51. Myself
  52. You
  53. and 4000
  54. Hungry
  55. Later 6000
  56. Food 10000


A second example:

Java code
  1. Import java.util.*;
  2. Public class Namesort {
  3. public static void Main (string[] args) {
  4. Name[] NameArray = { new Name ("John", "Lennon"),
  5. New name ("Karl", "Marx"), new name ("Groucho", "Marx"),
  6. New Name ("Oscar", "Grouch")};
  7. Arrays.sort (NameArray); Sorts the specified array of objects in ascending order based on the natural ordering of the elements. All elements in an array must implement an Comparable interface. In addition, all meta//elements in the array must be comparable (that is, for any E1 and E2 element in the array, theE1 . CompareTo (E2) shall not throw classcastexception).
  8. For (int i = 0; i < namearray.length; i++) {
  9. System.out.println (Namearray[i].tostring ());
  10. }
  11. }
  12. }
  13. Class Name implements Comparable<name> {
  14. Public String FirstName, LastName;
  15. Public Name (string firstName, String lastName) {
  16. this.firstname = firstName;
  17. this.lastname = lastName;
  18. }
  19. public int compareTo (Name o) { //Implement Interface
  20. int lastcmp = Lastname.compareto (o.lastname);
  21. //First compare surname (LastName) if last name is the same (lastcmp==0) then compare name (FirstName), otherwise the return name is compared
  22. return (lastcmp = = 0 Firstname.compareto (o.firstname): LASTCMP);
  23. }
  24. Public String toString () { //easy to output test
  25. return firstName + "" + lastName;
  26. }
  27. }
  28. Output Result:
  29. Oscar Grouch
  30. John Lennon
  31. Groucho Marx
  32. Karl Marx

Java code
    1. Look at this beautiful application of the trinocular operator Oh!
    2. public int compareTo (Pair o) {
    3. int cmp = Number-o.number;
    4. return (cmp = = 0 Name.compareto (o.name): CMP);
    5. }
    6. ----------------------
    7. public int compareTo (Name o) { //Implement Interface
    8. int lastcmp = Lastname.compareto (o.lastname);
    9. //First compare surname (LastName) if last name is the same (lastcmp==0) then compare name (FirstName), otherwise the return name is compared
    10. return (lastcmp = = 0 Firstname.compareto (o.firstname): LASTCMP);
      1. }


        This article reprinted to: http://ocaicai.iteye.com/blog/794438

Sort objects, CompareTo

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.