我有一个人员对象的数组列表,每个对象都有名字、姓氏和年龄。我想使用内部类提供一种按名字对这些对象进行排序的方法。
我如何访问内部类中重写的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;
}
}
}
小唯快跑啊
相关分类