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

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


我如何访问内部类中重写的compareTo方法?我想使用内部类,因为一旦按名字排序起作用,我将创建内部类以按其他属性排序。


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;

        }


    }


}


一只斗牛犬
浏览 77回答 1
1回答

小唯快跑啊

类比较名字class compareFirstName implements Comparator<Person>{@overridepublic int compareTo(Person p1,Person p2){return p1.getFirstName().compareTo(p2.getFirstName());}}在您的主要方法上创建上述类的实例并使用 Collections 类进行排序compareFirstName c = new compareFirstName ();List<Person> yourPersonList = new ArrayList<>();.........................Collections.sort(yourPersonList, c);for(Person p : yourPersonList) {&nbsp; System.out.println(p.getFirstName()+","+p.getLastName()+","+p.getAge());}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java