定义一个 Person 类。 属性有: 姓名、 收入、 年龄、 书(一本)。 定义一个 Book 类; 属性有: 书名、 价格。 要求用 Comparable 接口实现, 使用 TreeSet<Person>集合存储, 排序规则: A. 先按照收入从高到低排序; B. 收入相等的情况下, 按照年龄从小到大排序; C. 如果收入和年龄都相等, 按照姓名排序, 字典顺序(String 类的 compareTo 方法); D. 如果以上 3 个属性都相等, 按照书排序, 先按照书价格从低到高, 如果书价格相等, 按照书名(字典顺序)。用java实现
时间: 2023-06-19 19:05:01 浏览: 109
下面是实现代码:
Person类:
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 o) {
int result = Integer.compare(o.income, this.income);
if (result != 0) {
return result;
}
result = Integer.compare(this.age, o.age);
if (result != 0) {
return result;
}
result = this.name.compareTo(o.name);
if (result != 0) {
return result;
}
return Comparator.comparing(Book::getPrice).thenComparing(Book::getName).compare(this.book, o.book);
}
}
Book类:
public class 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;
}
}
测试代码:
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
Book book1 = new Book("Java编程思想", 100);
Book book2 = new Book("深入浅出设计模式", 80);
Book book3 = new Book("Effective Java", 120);
TreeSet<Person> set = new TreeSet<>();
set.add(new Person("张三", 100000, 25, book1));
set.add(new Person("李四", 80000, 30, book2));
set.add(new Person("王五", 120000, 20, book3));
for (Person person : set) {
System.out.println(person.getName() + " " + person.getIncome() + " " + person.getAge() + " " + person.getBook().getName() + " " + person.getBook().getPrice());
}
}
}
输出结果:
王五 120000 20 Effective Java 120
张三 100000 25 Java编程思想 100
李四 80000 30 深入浅出设计模式 80
阅读全文