利用自定义比较器 Comparator 实现类完成定义一个 Person 类。 属性有: 姓名、 收入、 年龄、 书(一本)。 定义一个 Book 类; 属性有: 书名、 价格。A. 先按照收入从高到低排序; B. 收入相等的情况下, 按照年龄从小到大排序; C. 如果收入和年龄都相等, 按照姓名排序, 字典顺序(String 类的 compareTo 方法); D. 如果以上 3 个属性都相等, 按照书排序, 先按照书价格从低到高, 如果书价格相等, 按照书名(字典顺序)。
时间: 2023-06-24 10:08:44 浏览: 71
下面是实现类的代码,其中使用了 Comparator 接口来定义比较规则:
```
import java.util.Comparator;
public class Person implements Comparable<Person> {
private String name;
private int income;
private int age;
private Book book;
public Person(String name, int income, int age, Book book) {
this.name = name;
this.income = income;
this.age = age;
this.book = book;
}
public String getName() {
return name;
}
public int getIncome() {
return income;
}
public int getAge() {
return age;
}
public Book getBook() {
return book;
}
@Override
public int compareTo(Person p) {
int cmp = Integer.compare(p.getIncome(), this.income);
if (cmp != 0) {
return cmp;
}
cmp = Integer.compare(this.age, p.getAge());
if (cmp != 0) {
return cmp;
}
cmp = this.name.compareTo(p.getName());
if (cmp != 0) {
return cmp;
}
return this.book.compareTo(p.getBook());
}
public static Comparator<Person> getComparator() {
return new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.compareTo(p2);
}
};
}
}
class Book implements Comparable<Book> {
private String name;
private int price;
public Book(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
@Override
public int compareTo(Book b) {
int cmp = Integer.compare(this.price, b.getPrice());
if (cmp != 0) {
return cmp;
}
return this.name.compareTo(b.getName());
}
}
```
使用方法:
```
// 创建两个 Person 对象
Person p1 = new Person("Tom", 5000, 25, new Book("Java", 50));
Person p2 = new Person("Jerry", 5000, 24, new Book("Python", 40));
// 使用自定义比较器进行排序
List<Person> list = new ArrayList<>();
list.add(p1);
list.add(p2);
Collections.sort(list, Person.getComparator());
// 输出排序结果
for (Person p : list) {
System.out.println(p.getName() + " " + p.getIncome() + " " + p.getAge() + " " + p.getBook().getName() + " " + p.getBook().getPrice());
}
```
输出结果:
```
Tom 5000 25 Java 50
Jerry 5000 24 Python 40
```
阅读全文