使用Arrays.sort()方法对对象类型的数组进行排序

3

我知道如何使用Arrays.sort()方法按以下方式对对象数组进行排序。

Arrays.sort(array of primitive type);   
Arrays.sort(array of primitive type, from, to); 
Arrays.sort(array of an object type);   
Arrays.sort(array of an object type , from, to);    

但是我对以下两种方法一无所知。

Arrays.sort(array of an object type , comparator);  
Arrays.sort(array of an object type , from, to, comparator);    

请问怎样使用这些方法对对象类型的数组进行排序?如果可以,请附上代码或指向.java类的链接。我已经尝试搜索,但未能找到。

谢谢。


1
请查看Comparator的文档。您需要实现一个Comparator来使用您所询问的方法。 - jahroy
1
寻找特定Java类的文档应该非常容易。你只需要在谷歌上搜索java 7 类名。比如,在这个例子中,搜索:java 7 Comparator。如果你正在查看Arrays类的文档,那里有多个链接指向Comparator的文档。 - jahroy
4个回答

5
示例:
class Person{  
   int id;  
   public getId(){return this.id;}  
//Other  stuff in your custom class
}  

Person[] persons = ...;//An array of person you get from somewhere
Arrays.sort(persons,new Comparator<Person>(){  
    @Override  
    public int compare(Person p1, Person p2){  
         return p1.getId() - p2.getId();  
   }  
} ); 

1

很简单:

比较器接口可以让您控制对象的排序方式。

一个对象可以基于一个关键字,这是您的智慧。

例如,账户对象应该根据账户号码进行排序。

class Account {
    String AccountNumber; //Key 1 
    String AccountName;   //Key 2
    String GovtID;        //Key 3 
}

你可以根据三个关键字之一进行排序。
为了控制排序,您需要定义一个实现Comparator接口的类,该类将定义用于排序的逻辑。
class SortAccountByNumber implements Comparator<Account> {
    //Implement Unimplemented method 
    @Override
    public int compare(Account a1, Account a2) {
        //Read the specification for this method here in the Java Doc.
        return 0;
    }

}

现在要使用这个功能,只需调用:


  SortAccountByNumber varSortAccountByNumber = new SortAccountByNumber();
  Arrays.sort(arrayOfAccounts,varSortAccountByNumber);

0
这是一个比较器没有内联定义的示例。
两种方式都可以接受,但我认为这种方式更容易理解。
class Person {
   int id;  
   public getId(){
       return this.id;
   }  
}

class PersonComparator implements Comparator<Person> {
    @Override
    public int compareTo(Person personOne, Person personTwo) {
        reuturn personOne.getId() - personTwo.getId();
    }
}

使用方法:

Person[] personArray = buildArraySomehow();
PersonComparator pc = new PersonComparator();
Arrays.sort(personArray, pc);

Comparator 是一个只有一个方法 compareTo 的接口。

当你创建 Comparator 时,这是唯一需要实现的方法。

请注意,PersonComparator.compareTo() 除了返回两个 Person 对象的 ID 差异之外什么也不做。

这是因为 compareTo() 方法应该如何工作:

  • 如果第一个项目“在前面”,则应返回负数。
  • 如果第一个项目“在后面”,则应返回正数。
  • 如果两个项目在排序上相等,则应返回零。

查看 Comparator 文档以了解更多信息...


0

对于复杂对象,Java 不知道如何进行比较。因此,您需要编写一个 Comparator。通常情况下,您选择要进行比较的类成员。

public class Comp implements Comparator<Test> {

    @Override
    public int compare(Test t, Test t1) {
       return what_you_want_to_compare;
    }    
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接