# Java 中的`Comparable`接口

> 原文： [https://beginnersbook.com/2017/08/comparable-interface-in-java-with-example/](https://beginnersbook.com/2017/08/comparable-interface-in-java-with-example/)

**`Comparable`接口**主要用于对**自定义对象**的数组（或列表）进行排序。
实现`Comparable`接口的对象列表（和数组）可以由`Collections.sort`（和`Arrays.sort`）自动排序。在我们看到如何对自定义对象的对象进行排序之前，让我们看看如何对已经实现 `Comparable`的数组元素和包装器类进行排序。

## 示例：对数组和包装器类进行排序

```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Demo {
  public static void main(String[] args) {
    /*
     * Integer class implements Comparable
     * Interface so we can use the sort method
     */
    int[] arr = {11,55,22,0,89};
    Arrays.sort(arr);
    System.out.print("Sorted Int Array: ");
    System.out.println(Arrays.toString(arr));

    /*
     * String class implements Comparable
     * Interface so we can use the sort method
     */
    System.out.print("Sorted String Array: ");
    String[] names = {"Steve", "Ajeet", "Kyle"};
    Arrays.sort(names);
    System.out.println(Arrays.toString(names));

     /*
      * String class implements Comparable
      * Interface so we can use the sort method
      */
     System.out.print("Sorted List: ");
     List fruits = new ArrayList();
     fruits.add("Orange");
     fruits.add("Banana");
     fruits.add("Apple");
     fruits.add("Guava");
     fruits.add("Grapes");
     Collections.sort(fruits);
     for(String s: fruits) System.out.print(s+", ");
  }
}

```

**输出：**

```java
Sorted Int Array: [0, 11, 22, 55, 89]
Sorted String Array: [Ajeet, Kyle, Steve]
Sorted List: Apple, Banana, Grapes, Guava, Orange, 

```

在上面的示例中，您已经看到对实现`Comparable`接口的数组和对象列表进行排序是多么容易，您只需要调用`Collections.sort`（和`Arrays.sort`）。
**但是，如果要对自定义类的对象进行排序，则需要在自定义类中实现`Comparable`接口。**

该接口只有一个方法：

```java
public abstract int compareTo(T obj)
```

由于此方法是抽象的，因此如果实现`Comparable`接口，则必须在类中实现此方法。

让我们举个例子来更好地理解这个：

## 示例：通过实现`Comparable`接口对自定义对象进行排序

正如您所看到的，我在`Author`类中实现了`Comparable`接口，因为我想对这个类的对象进行排序。我已经在`compareTo()`方法中编写了排序逻辑，您可以根据需求编写逻辑。我想先按姓氏排序作者姓名，如果姓氏相同，则按名字排序。如果您只想按姓氏排序，那么`compareTo()`方法中的第一行就足够了。

**`Author`类**

```java
public class Author implements Comparable<Author> {

  String firstName;
  String lastName;
  String bookName;
  Author(String first, String last, String book){
	this.firstName = first;
	this.lastName = last;
	this.bookName = book;
  }

  @Override
  /*
   * This is where we write the logic to sort. This method sort 
   * automatically by the first name in case that the last name is 
   * the same.
   */
  public int compareTo(Author au){
     /* 
      * Sorting by last name. compareTo should return < 0 if this(keyword) 
      * is supposed to be less than au, > 0 if this is supposed to be 
      * greater than object au and 0 if they are supposed to be equal.
      */
     int last = this.lastName.compareTo(au.lastName);
     //Sorting by first name if last name is same d
     return last == 0 ? this.firstName.compareTo(au.firstName) : last;
  }
}

```

**排序类：`SortAuthByNames`**

```java
import java.util.ArrayList;   
import java.util.Collections;
public class SortAuthByNames{  
   public static void main(String args[]){  
      // List of objects of Author class
      ArrayList<Author> al=new ArrayList<Author>(); 
      al.add(new Author("Henry","Miller", "Tropic of Cancer"));  
      al.add(new Author("Nalo","Hopkinson", "Brown Girl in the Ring"));
      al.add(new Author("Frank","Miller", "300"));
      al.add(new Author("Deborah","Hopkinson", "Sky Boys"));
      al.add(new Author("George R. R.","Martin", "Song of Ice and Fire"));

      /*
       * Sorting the list using Collections.sort() method, we
       * can use this method because we have implemented the 
       * Comparable interface in our user defined class Author
       */
      Collections.sort(al);  
      for(Author str:al){  
    	  System.out.println(str.firstName+" "+
          str.lastName+" "+"Book: "+str.bookName);  
      } 
   }  
}  

```

**输出：**

```java
Deborah Hopkinson Book: Sky Boys
Nalo Hopkinson Book: Brown Girl in the Ring
George R. R. Martin Book: A Song of Ice and Fire
Frank Miller Book: 300
Henry Miller Book: Tropic of Cancer
```

> 注意：我们应该以这样的方式编写`compareTo()`方法：如果这个（我在这里指的是`this`关键字）小于传递的对象那么它应该返回负数，如果大于正数则为零，如果相等则返回 0。

你可能想知道为什么我没有写那个逻辑？因为名字和姓氏是字符串，所以我调用了字符串类的[`compareTo()`方法](https://beginnersbook.com/2013/12/java-string-compareto-method-example/)，它完全相同。

但是如果我们比较的东西是其他类型的东西，比如`int`那么你就可以编写这样的逻辑：
假设`Employee`类的对象是（`empId`，`empName`，`empAge`），我们想通过`empAge`对对象进行排序]。

```java
public int compareTo(Employee e){  
   if(this.empAge==e.empAge)  
      return 0;  
   else if(this.empAge>e.empAge)  
      return 1;  
   else  
      return -1;  
}
```

**或**

```java
public int compareTo(Employee e){  
return this.empAge > e.empAge ? 1 : this.empAge < e.empAge ? -1 : 0;
}
```