Java 简明教程

Java - How to Use Comparable?

Java Comparable Interface

Comparable interface 是一个非常重要的接口,可以由 Java Collections 用于比较自定义 objects 并对其进行排序。使用 comparable 接口,我们可以对自定义对象进行排序,与 wrapper classesstring 对象使用 Collections 排序方法进行排序的方式相同。

Comparable interface is a very important interface which can be used by Java Collections to compare custom objects and sort them. Using comparable interface, we can sort our custom objects in the same way how wrapper classes, string objects get sorted using Collections sorting methods.

使用 Comparable,我们可以让元素可排序。

Using comparable, we can make the elements as sortable.

Comparable Interface Methods

Comparable 接口定义了方法 compareTo()。此处所示的 compareTo() 方法比较了用于排序的传递对象 -

The Comparable interface defines a methods: compareTo(). The compareTo() method, shown here, compares the passed object for order −

The compare() Method

int compareTo(Object obj)

obj 是要比较的对象。如果对象相等,此方法将返回零。如果当前对象大于 obj,则此方法将返回正值。否则,它将返回负值。

obj is the object to be compared. This method returns zero if the objects are equal. It returns a positive value if current object is greater than obj. Otherwise, a negative value is returned.

通过覆盖 compareTo(),你可以改变对象排序的方式。例如,要按相反顺序排序,你可以实现一个比较方法来反转比较结果。

By overriding compareTo(), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can implement a comparison method that reverses the outcome of a comparison.

The equals() Method

下面所示的 equals() 方法测试一个对象是否等于调用比较器 −

The equals() method, shown here, tests whether an object equals the invoking comparator −

boolean equals(Object obj)

obj 是要测试是否相等的对象。如果 obj 和调用对象都是 Comparator 对象并且使用相同的排序,则该方法返回 true。否则,它将返回 false。

obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false.

覆盖 equals() 并非必要,并且大多数简单的比较器不会这样做。

Overriding equals() is unnecessary, and most simple comparators will not do so.

Comparable Interface to Sort Custom Object

在这个示例中,我们使用 Comparable 接口对自定义对象 Dog 依据排序条件进行排序。

In this example, we’re using Comparable interface to sort a custom object Dog based on comparison criterias.

Example

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

class Dog implements Comparable<Dog> {
   private String name;
   private int age;
   Dog() {
   }

   Dog(String n, int a) {
      name = n;
      age = a;
   }

   public String getDogName() {
      return name;
   }

   public int getDogAge() {
      return age;
   }

   // Overriding the compareTo method
   public int compareTo(Dog d) {
      // compare the name using alphabetical order
      return (this.name).compareTo(d.name);
   }

   @Override
   public String toString() {
      return this.name + "," + this.age;
   }
}

public class ComparableDemo {

   public static void main(String args[]) {
      // Takes a list o Dog objects
      List<Dog> list = new ArrayList<>();

      list.add(new Dog("Shaggy", 3));
      list.add(new Dog("Lacy", 2));
      list.add(new Dog("Roger", 10));
      list.add(new Dog("Tommy", 4));
      list.add(new Dog("Tammy", 1));

      Collections.sort(list);   // Sorts the array list
      System.out.println("Sorted by name:");
      // printing the sorted list of names
      System.out.print(list);
   }
}

这会产生以下结果 −

This will produce the following result −

Sorted by name:
[Lacy,2, Roger,10, Shaggy,3, Tammy,1, Tommy,4]

Note - Arrays class 的排序与 Collections 相同。

Note − Sorting of the Arrays class is as the same as the Collections.

Comparable Interface to Sort Custom Object in Reverse Order

Example

在这个例子中,我们使用 Collections.reverseOrder() method 来反向排序 Dog 对象。

In this example, we’re using Collections.reverseOrder() method to reverse sort the Dog objects.

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

class Dog implements Comparable<Dog> {
   private String name;
   private int age;
   Dog() {
   }

   Dog(String n, int a) {
      name = n;
      age = a;
   }

   public String getDogName() {
      return name;
   }

   public int getDogAge() {
      return age;
   }

   // Overriding the compareTo method
   public int compareTo(Dog d) {
      return (this.name).compareTo(d.name);
   }

   @Override
   public String toString() {
      return this.name + "," + this.age;
   }
}

public class ComparableDemo {

   public static void main(String args[]) {
      // Takes a list o Dog objects
      List<Dog> list = new ArrayList<>();

      list.add(new Dog("Shaggy", 3));
      list.add(new Dog("Lacy", 2));
      list.add(new Dog("Roger", 10));
      list.add(new Dog("Tommy", 4));
      list.add(new Dog("Tammy", 1));

      Collections.sort(list, Collections.reverseOrder());   // Sorts the array list
      System.out.println("Sorted by name in reverse order:");
      // printing the sorted list of names
      System.out.print(list);
   }
}

这会产生以下结果 −

This will produce the following result −

Sorted by name in reverse order:
[Tommy,4, Tammy,1, Shaggy,3, Roger,10, Lacy,2]

Example

在这个示例中,我们使用 Comparable 接口依据年龄对 Dog 对象进行排序。

In this example, we’re using Comparable interface to sort Dog objects based on their ages.

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

class Dog implements Comparable<Dog> {
   private String name;
   private int age;
   Dog() {
   }

   Dog(String n, int a) {
      name = n;
      age = a;
   }

   public String getDogName() {
      return name;
   }

   public int getDogAge() {
      return age;
   }

   // Overriding the compareTo method
   public int compareTo(Dog d) {
      return this.age - d.age;
   }

   @Override
   public String toString() {
      return this.name + "," + this.age;
   }
}

public class ComparableDemo {

   public static void main(String args[]) {
      // Takes a list o Dog objects
      List<Dog> list = new ArrayList<>();

      list.add(new Dog("Shaggy", 3));
      list.add(new Dog("Lacy", 2));
      list.add(new Dog("Roger", 10));
      list.add(new Dog("Tommy", 4));
      list.add(new Dog("Tammy", 1));

      Collections.sort(list);   // Sorts the array list
      System.out.println("Sorted by age:");
      // printing the sorted list by age
      System.out.print(list);
   }
}

这会产生以下结果 −

This will produce the following result −

Sorted by age:
[Tammy,1, Lacy,2, Shaggy,3, Tommy,4, Roger,10]