通过在内部 class 中实现 Comparable 来提供多种排序选项

Providing multiple sort options by implementing Comparable in inner class

我有一个人对象数组列表,每个对象都有名字、姓氏和年龄。我想使用内部 class 来提供一种按名字对这些对象进行排序的方法。

如何访问内部 class 中被覆盖的 compareTo 方法?我想使用 inner classes 因为一旦按名字排序有效,我将创建 inner classes 以按其他属性排序。

package listdemo;

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

public class ListDemo {
    public static void main(String[] args) {

        List<Person> people = new ArrayList<>();

        people.add(new Person("Homer", "Simpson", 29));
        people.add(new Person("Mo", "Sizlak", 23));
        people.add(new Person("Bart", "Simpson", 22));
        people.add(new Person("Peter", "Griffin", 30));
        people.add(new Person("Joe", "Swanson", 27));

    }
}

package listdemo;

public class Person {
    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;

        //create an instance of the inner class upon initialization of Person
        Person.CompareFirstName compareFirstName = this.new CompareFirstName();
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

    class CompareFirstName implements Comparable<Person> {

        @Override
        public int compareTo(Person comparePerson) {
            System.out.println("inner class compareTo method invoked");
            int difference = Person.this.firstName.compareTo(comparePerson.getFirstName());
            return difference;
        }

    }

}

class compareFirstName

class compareFirstName implements Comparator<Person>{
@override
public int compareTo(Person p1,Person p2){
return p1.getFirstName().compareTo(p2.getFirstName());
}
}

在你的 main 方法上创建上面的实例 class 并使用 Collections class 来排序

compareFirstName c = new compareFirstName ();
List<Person> yourPersonList = new ArrayList<>();
.........................
Collections.sort(yourPersonList, c);
for(Person p : yourPersonList) {
  System.out.println(p.getFirstName()+","+p.getLastName()+","+p.getAge());
}