Java 集合 Comparable接口

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

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

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+", ");
  }
}

输出:

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接口。

该接口只有一个方法:

public abstract int compareTo(T obj)

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

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

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

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

Author

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

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);  
      } 
   }  
}  

输出:

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()方法,它完全相同。

但是如果我们比较的东西是其他类型的东西,比如int那么你就可以编写这样的逻辑:
假设Employee类的对象是(empIdempNameempAge),我们想通过empAge对对象进行排序]。

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

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程