为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只斗牛犬 2023-09-27 10:24:11
我有一个人员对象的数组列表,每个对象都有名字、姓氏和年龄。我想使用内部类提供一种按名字对这些对象进行排序的方法。我如何访问内部类中重写的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;        }    }}
查看完整描述

1 回答

?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

类比较名字


class compareFirstName implements Comparator<Person>{

@override

public 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) {

  System.out.println(p.getFirstName()+","+p.getLastName()+","+p.getAge());

}


查看完整回答
反对 回复 2023-09-27
  • 1 回答
  • 0 关注
  • 76 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信