按字段排序对象数组

use*_*280 3 java arrays sorting field object

我有对象

Person{
    String name;  
    int age;
    float gradeAverage;
    }
Run Code Online (Sandbox Code Playgroud)

有一种简单的排序方式

Person[] ArrayOfPersons
Run Code Online (Sandbox Code Playgroud)

按年龄?

我必须使用Comparable或Comparator吗?我不完全理解他们.

tob*_*s_k 15

为了完整起见,在使用Java 8时,您可以使用Comparator.comparing为某些属性创建一个简单的比较器,例如Comparator.comparing(Person::getAge),或者使用lambda,例如Comparator.comparing(p -> p.age),如果没有年龄的getter方法.

这使得为不同属性链接比较器变得特别容易thenComparing,例如主要按年龄排序,然后在关系情况下按名称排序:

Comparator.comparing(Person::getAge).thenComparing(Person::getName)
Run Code Online (Sandbox Code Playgroud)

结合它Arrays.sort,你就完成了.

Arrays.sort(arrayOfPersons, Comparator.comparing(Person::getAge));
Run Code Online (Sandbox Code Playgroud)


Abd*_*ady 5

您可以在循环中使用 getter 检查年龄

for (int i = 0 ; i < persons.length - 1; i++) {
    Person p = persons[i];
    Person next =  persons[i+1];
    if(p.getAge() > next.getAge()) {
        // Swap
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,实现 Comparable 是一种方便的方法

class Person implements Comparable<Person> {
    String name;  
    int age;
    float gradeAverage;

    public int compareTo(Person other) {
        if(this.getAge() > other.getAge())
            return 1;
        else if (this.getAge() == other.getAge())
            return 0 ;
        return -1 ;
    }

    public int getAge() {
        return this.age ;
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以检查Comparable文档