# Java `ArrayList`对象排序（`Comparable`和`Comparator`）

> 原文： [https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/](https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/)

在本教程中，我们将看到**如何使用[可比较对象](https://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html)和[比较器](https://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html)接口按属性**对对象的`ArrayList`进行排序。如果您正在寻找对`String`或`Integer`的简单`ArrayList`进行排序，那么您可以参考以下教程 -

*   [`ArrayList<String>`和`ArrayList<Integer>`的排序](https://beginnersbook.com/2013/12/how-to-sort-arraylist-in-java/)
*   [按降序排序`ArrayList`](https://beginnersbook.com/2013/12/sort-arraylist-in-descending-order-in-java/)

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

## 为什么需要`Comparable`和`Comparator`？

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

```java
public class Student  {
    private String studentname;
    private int rollno;
    private int studentage;

    public Student(int rollno, String studentname, int studentage) {
         this.rollno = rollno;
         this.studentname = studentname;
         this.studentage = studentage;
    }

    public String getStudentname() {
         return studentname;
    }
    public void setStudentname(String studentname) {
	this.studentname = studentname;
    }
    public int getRollno() {
	return rollno;
    }
    public void setRollno(int rollno) {
	this.rollno = rollno;
    }
    public int getStudentage() {
	return studentage;
    }
    public void setStudentage(int studentage) {
 	this.studentage = studentage;
    }	
}
```

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

```java
import java.util.*;
public class ArrayListSorting  {

     public static void main(String args[]){
	   ArrayList<Student> arraylist = new ArrayList<Student>();
	   arraylist.add(new Student(223, "Chaitanya", 26));
	   arraylist.add(new Student(245, "Rahul", 24));
	   arraylist.add(new Student(209, "Ajeet", 32));

	   Collections.sort(arraylist);

	   for(Student str: arraylist){
			System.out.println(str);
	   }
     }
}
```

我试图在对象列表上调用`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`方法，除非我们使用`Comparable`和`Comparator`之类的接口，否则它实际上不起作用。

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

## 使用`Comparable`排序`ArrayList<Object>`

假设我们需要对`ArrayList<Student>`进行排序。根据学生年龄属性。这是如何做到的 - 首先实现`Comparable`接口，然后覆盖[`compareTo`](https://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html#compareTo(T))方法。

```java
package beginnersbook.com;

public class Student implements Comparable {
    private String studentname;
    private int rollno;
    private int studentage;

    public Student(int rollno, String studentname, int studentage) {
        this.rollno = rollno;
        this.studentname = studentname;
        this.studentage = studentage;
    }
    ...
    //getter and setter methods same as the above example 
    ...
    @Override
    public int compareTo(Student comparestu) {
        int compareage=((Student)comparestu).getStudentage();
        /* For Ascending order*/
        return this.studentage-compareage;

        /* For Descending order do like this */
        //return compareage-this.studentage;
    }

    @Override
    public String toString() {
        return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
    }

}
```

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

```java
import java.util.*;
public class ArrayListSorting  {

	public static void main(String args[]){
	   ArrayList<Student> arraylist = new ArrayList<Student>();
	   arraylist.add(new Student(223, "Chaitanya", 26));
	   arraylist.add(new Student(245, "Rahul", 24));
	   arraylist.add(new Student(209, "Ajeet", 32));

	   Collections.sort(arraylist);

	   for(Student str: arraylist){
			System.out.println(str);
	   }
	}
}
```

输出：

```java
[ rollno=245, name=Rahul, age=24]
[ rollno=223, name=Chaitanya, age=26]
[ rollno=209, name=Ajeet, age=32]
```

**`Comparable`做了我们的工作为什么我们需要`Comparator`了？**

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

1.  [Java `Comparable`](https://beginnersbook.com/2017/08/comparable-interface-in-java-with-example/)
2.  [Java `Comparator`](https://beginnersbook.com/2017/08/comparator-interface-in-java/)

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

我们优先使用`Comparator`的[`compare`](https://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html#compare(T, T))方法进行排序。

```java
package beginnersbook.com;
import java.util.Comparator;
public class Student  {
    private String studentname;
    private int rollno;
    private int studentage;

    public Student(int rollno, String studentname, int studentage) {
        this.rollno = rollno;
        this.studentname = studentname;
        this.studentage = studentage;
    }
    ...
    //Getter and setter methods same as the above examples
    ...
    /*Comparator for sorting the list by Student Name*/
    public static Comparator<Student> StuNameComparator = new Comparator<Student>() {

	public int compare(Student s1, Student s2) {
	   String StudentName1 = s1.getStudentname().toUpperCase();
	   String StudentName2 = s2.getStudentname().toUpperCase();

	   //ascending order
	   return StudentName1.compareTo(StudentName2);

	   //descending order
	   //return StudentName2.compareTo(StudentName1);
    }};

    /*Comparator for sorting the list by roll no*/
    public static Comparator<Student> StuRollno = new Comparator<Student>() {

	public int compare(Student s1, Student s2) {

	   int rollno1 = s1.getRollno();
	   int rollno2 = s2.getRollno();

	   /*For ascending order*/
	   return rollno1-rollno2;

	   /*For descending order*/
	   //rollno2-rollno1;
   }};
    @Override
    public String toString() {
        return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
    }

}
```

`ArrayList`类：

```java
package beginnersbook.com;
import java.util.*;
public class Details  {

	public static void main(String args[]){
	   ArrayList<Student> arraylist = new ArrayList<Student>();
	   arraylist.add(new Student(101, "Zues", 26));
	   arraylist.add(new Student(505, "Abey", 24));
	   arraylist.add(new Student(809, "Vignesh", 32));

	   /*Sorting based on Student Name*/
	   System.out.println("Student Name Sorting:");
	   Collections.sort(arraylist, Student.StuNameComparator);

	   for(Student str: arraylist){
			System.out.println(str);
	   }

	   /* Sorting on Rollno property*/
	   System.out.println("RollNum Sorting:");
	   Collections.sort(arraylist, Student.StuRollno);
	   for(Student str: arraylist){
			System.out.println(str);
	   }
	}
}
```

输出：

```java
Student Name Sorting:
[ rollno=505, name=Abey, age=24]
[ rollno=809, name=Vignesh, age=32]
[ rollno=101, name=Zues, age=26]
RollNum Sorting:
[ rollno=101, name=Zues, age=26]
[ rollno=505, name=Abey, age=24]
[ rollno=809, name=Vignesh, age=32]
```