原文: https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/

在本教程中,我们将看到如何使用可比较对象比较器接口按属性对对象的ArrayList进行排序。如果您正在寻找对StringInteger的简单ArrayList进行排序,那么您可以参考以下教程 -

我们通常使用Collections.sort()方法对一个简单的ArrayList进行排序。但是,如果ArrayList自定义对象类型,那么在这种情况下,您有两个选项可用于排序 - 可比较和比较器接口。在介绍它们的示例之前,让我们看看当我们尝试对对象的arraylist进行排序而不实现任何这些接口时的输出是什么。

为什么需要ComparableComparator

考虑下面的例子 - 我有一个 Student 类,它具有学生姓名,掷骰号和学生年龄等属性。

  1. public class Student {
  2. private String studentname;
  3. private int rollno;
  4. private int studentage;
  5. public Student(int rollno, String studentname, int studentage) {
  6. this.rollno = rollno;
  7. this.studentname = studentname;
  8. this.studentage = studentage;
  9. }
  10. public String getStudentname() {
  11. return studentname;
  12. }
  13. public void setStudentname(String studentname) {
  14. this.studentname = studentname;
  15. }
  16. public int getRollno() {
  17. return rollno;
  18. }
  19. public void setRollno(int rollno) {
  20. this.rollno = rollno;
  21. }
  22. public int getStudentage() {
  23. return studentage;
  24. }
  25. public void setStudentage(int studentage) {
  26. this.studentage = studentage;
  27. }
  28. }

我想要一个学生对象的ArrayList。我们这样做 -

  1. import java.util.*;
  2. public class ArrayListSorting {
  3. public static void main(String args[]){
  4. ArrayList<Student> arraylist = new ArrayList<Student>();
  5. arraylist.add(new Student(223, "Chaitanya", 26));
  6. arraylist.add(new Student(245, "Rahul", 24));
  7. arraylist.add(new Student(209, "Ajeet", 32));
  8. Collections.sort(arraylist);
  9. for(Student str: arraylist){
  10. System.out.println(str);
  11. }
  12. }
  13. }

我试图在对象列表上调用Collections.sort()并繁荣!我得到了这样的错误信息 -
线程main中的异常java.lang.Error:未解决的编译问题:
Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments (ArrayList). The inferred type Student is not a valid substitute for the bounded parameter &gt; at beginnersbook.com.Details.main(Details.java:11)

原因:我刚刚在对象的ArrayList上调用了sort方法,除非我们使用ComparableComparator之类的接口,否则它实际上不起作用。

现在您必须了解这些接口的重要性。让我们看看如何使用它们以我们的方式完成排序。

使用Comparable排序ArrayList<Object>

假设我们需要对ArrayList<Student>进行排序。根据学生年龄属性。这是如何做到的 - 首先实现Comparable接口,然后覆盖compareTo)方法。

  1. package beginnersbook.com;
  2. public class Student implements Comparable {
  3. private String studentname;
  4. private int rollno;
  5. private int studentage;
  6. public Student(int rollno, String studentname, int studentage) {
  7. this.rollno = rollno;
  8. this.studentname = studentname;
  9. this.studentage = studentage;
  10. }
  11. ...
  12. //getter and setter methods same as the above example
  13. ...
  14. @Override
  15. public int compareTo(Student comparestu) {
  16. int compareage=((Student)comparestu).getStudentage();
  17. /* For Ascending order*/
  18. return this.studentage-compareage;
  19. /* For Descending order do like this */
  20. //return compareage-this.studentage;
  21. }
  22. @Override
  23. public String toString() {
  24. return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
  25. }
  26. }

现在我们可以在ArrayList上调用Collections.sort

  1. import java.util.*;
  2. public class ArrayListSorting {
  3. public static void main(String args[]){
  4. ArrayList<Student> arraylist = new ArrayList<Student>();
  5. arraylist.add(new Student(223, "Chaitanya", 26));
  6. arraylist.add(new Student(245, "Rahul", 24));
  7. arraylist.add(new Student(209, "Ajeet", 32));
  8. Collections.sort(arraylist);
  9. for(Student str: arraylist){
  10. System.out.println(str);
  11. }
  12. }
  13. }

输出:

  1. [ rollno=245, name=Rahul, age=24]
  2. [ rollno=223, name=Chaitanya, age=26]
  3. [ rollno=209, name=Ajeet, age=32]

Comparable做了我们的工作为什么我们需要Comparator了?

由于Comparable是由对象进行排序的同一个类实现的,所以它会绑定你的排序逻辑,在大多数情况下都可以,但是如果你想要的方法不仅仅是对类对象进行排序了应该使用比较器。在这里阅读更多相关信息:

  1. Java Comparable
  2. Java Comparator

使用Comparator的多个属性对ArrayList<Object>进行排序

我们优先使用Comparatorcompare(T, T))方法进行排序。

  1. package beginnersbook.com;
  2. import java.util.Comparator;
  3. public class Student {
  4. private String studentname;
  5. private int rollno;
  6. private int studentage;
  7. public Student(int rollno, String studentname, int studentage) {
  8. this.rollno = rollno;
  9. this.studentname = studentname;
  10. this.studentage = studentage;
  11. }
  12. ...
  13. //Getter and setter methods same as the above examples
  14. ...
  15. /*Comparator for sorting the list by Student Name*/
  16. public static Comparator<Student> StuNameComparator = new Comparator<Student>() {
  17. public int compare(Student s1, Student s2) {
  18. String StudentName1 = s1.getStudentname().toUpperCase();
  19. String StudentName2 = s2.getStudentname().toUpperCase();
  20. //ascending order
  21. return StudentName1.compareTo(StudentName2);
  22. //descending order
  23. //return StudentName2.compareTo(StudentName1);
  24. }};
  25. /*Comparator for sorting the list by roll no*/
  26. public static Comparator<Student> StuRollno = new Comparator<Student>() {
  27. public int compare(Student s1, Student s2) {
  28. int rollno1 = s1.getRollno();
  29. int rollno2 = s2.getRollno();
  30. /*For ascending order*/
  31. return rollno1-rollno2;
  32. /*For descending order*/
  33. //rollno2-rollno1;
  34. }};
  35. @Override
  36. public String toString() {
  37. return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
  38. }
  39. }

ArrayList类:

  1. package beginnersbook.com;
  2. import java.util.*;
  3. public class Details {
  4. public static void main(String args[]){
  5. ArrayList<Student> arraylist = new ArrayList<Student>();
  6. arraylist.add(new Student(101, "Zues", 26));
  7. arraylist.add(new Student(505, "Abey", 24));
  8. arraylist.add(new Student(809, "Vignesh", 32));
  9. /*Sorting based on Student Name*/
  10. System.out.println("Student Name Sorting:");
  11. Collections.sort(arraylist, Student.StuNameComparator);
  12. for(Student str: arraylist){
  13. System.out.println(str);
  14. }
  15. /* Sorting on Rollno property*/
  16. System.out.println("RollNum Sorting:");
  17. Collections.sort(arraylist, Student.StuRollno);
  18. for(Student str: arraylist){
  19. System.out.println(str);
  20. }
  21. }
  22. }

输出:

  1. Student Name Sorting:
  2. [ rollno=505, name=Abey, age=24]
  3. [ rollno=809, name=Vignesh, age=32]
  4. [ rollno=101, name=Zues, age=26]
  5. RollNum Sorting:
  6. [ rollno=101, name=Zues, age=26]
  7. [ rollno=505, name=Abey, age=24]
  8. [ rollno=809, name=Vignesh, age=32]