[Java development path] (21) Comparator and Comparable

Source: Internet
Author: User

[Java development path] (21) Comparator and Comparable

1. Comparable


  1. package java.lang;
  2. import java.util.*;
  3.  
  4.  
  5. public interface Comparable {
  6. public int compareTo(T o);
  7. }

Note:

Comparable is the sorting interface. If a class implements the Comparable interface, the class can support sorting. If there is a List (OR array) of instances that implement the Comparable interface, the List (OR array) can be sorted by Collections. sort (or Arrays. sort.

 

Suppose we use x. compareTo (y) to "compare the size of x and y ". If "negative" is returned, it means "x is smaller than y". If "zero" is returned, it means "x is equal to y". If "positive" is returned, it means "x is greater than y ".

Example:


  1. package com.qunar.test;
  2.  
  3. /**
  4. * Created by xiaosi on 16-3-7.
  5. */
  6. public class Student implements Comparable {
  7.  
  8. private String name;
  9. private int age;
  10.  
  11. public Student(String name, int age) {
  12. this.name = name;
  13. this.age = age;
  14. }
  15.  
  16. public String getName() {
  17. return name;
  18. }
  19.  
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23.  
  24. public int getAge() {
  25. return age;
  26. }
  27.  
  28. public void setAge(int age) {
  29. this.age = age;
  30. }
  31.  
  32. @Override
  33. public int compareTo(Student stu) {
  34. if(age == stu.getAge()){
  35. return name.compareTo(stu.getName());
  36. }//if
  37. else if(age > stu.getAge()){
  38. return 1;
  39. }
  40. return -1;
  41. }
  42. }

 


  1. List stus = new ArrayList ();
  2. stus.add(new Student("xiaosi",24));
  3. stus.add(new Student("sunny",24));
  4. stus.add(new Student("yoona",21));
  5. stus.add(new Student("kim",27));
  6.  
  7. Collections.sort(stus);
  8. for(Student stu : stus){
  9. System.out.println("age" + stu.getAge() + " name->" + stu.getName());
  10. }

The above example provides the following functions: sort by student age, and sort by name if the age is the same.

 

2. Comparator


  1. package java.util;
  2.  
  3.  
  4. public interface Comparator {
  5. int compare(T o1, T o2);
  6. boolean equals(Object obj);
  7. }

Note:

If a class does not support sorting, and the Comparable interface is not implemented. Then we can establish a comparator of this class for sorting. This Comparator only needs to implement the Comparator interface. We can use the comparator and then sort the classes through the comparator.

Example:


  1. package com.qunar.test;
  2.  
  3. /**
  4. * Created by xiaosi on 16-3-7.
  5. */
  6. public class Teacher {
  7. private String name;
  8. private int age;
  9.  
  10. public Teacher(String name, int age) {
  11. this.name = name;
  12. this.age = age;
  13. }
  14.  
  15. public String getName() {
  16. return name;
  17. }
  18.  
  19. public void setName(String name) {
  20. this.name = name;
  21. }
  22.  
  23. public int getAge() {
  24. return age;
  25. }
  26.  
  27. public void setAge(int age) {
  28. this.age = age;
  29. }
  30. }

Comparator:


  1. package com.qunar.test;
  2.  
  3. import java.util.Comparator;
  4.  
  5. /**
  6. * Created by xiaosi on 16-3-7.
  7. * Teacher Comparator
  8. */
  9. public class TeacherComparator implements Comparator {
  10.  
  11. @Override
  12. public int compare(Teacher o1, Teacher o2) {
  13. if(o1.getAge() == o2.getAge()){
  14. return o1.getName().compareTo(o2.getName());
  15. }//if
  16. else if(o1.getAge() > o2.getAge()){
  17. return 1;
  18. }
  19. return -1;
  20. }
  21. }


  1. List teachers = new ArrayList ();
  2. teachers.add(new Teacher("xiaosi",24));
  3. teachers.add(new Teacher("sunny",24));
  4. teachers.add(new Teacher("yoona",21));
  5. teachers.add(new Teacher("kim",27));
  6. Collections.sort(teachers,new TeacherComparator());
  7. for(Teacher te : teachers){
  8. System.out.println("age" + te.getAge() + " name->" + te.getName());
  9. }

3. Comparison

Comparable is an interface that supports self-comparison (such as String and Integer ). Comparator is a dedicated Comparator. When this object does not support auto-comparison or the auto-comparison function cannot meet your requirements, you can write a Comparator to compare the sizes of two objects. One is to complete the comparison by yourself, and the other is to compare the implementation of external programs.

Using Comparator is a strategy design pattern. Instead of changing the object itself, a strategy object is used to change its behavior. For example, if you want to sort Integers by absolute values, Integer does not meet the requirements. You do not need to modify the Integer class (you cannot actually do this) to change its sorting behavior, you only need to use an object that implements the Comparator interface to control its sorting.

Comparable usage: Write the comparison method to the object class and declare all comparison rules externally. In this way, the Code has poor universality. If a comparison rule is changed, the Code must be rewritten.

Use of Comparator: in this way, the entity and comparison rules are unbound. The comparison rules can be called based on your own business needs.

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.