2.定义一个Person类。属性有: 定义一个Book类; 属性有: 书名、 价格。 要求用Comparable接口实现, 使用TreeSet<Person>集合存储, 排序规则: A.先按照收入从高到低排序; B.收入相等的情况下, 按照年龄从小到大排序; C.如果收入和年龄都相等, 按照姓名排序, 字典顺序(String类的compareTo方法); D.如果以上3个属性都相等, 按照书排序, 先按照书价格从低到高, 如果书价格相等, 按照书名(字典顺序)。
时间: 2023-06-15 18:05:08 浏览: 83
Person类的定义如下:
```java
import java.util.TreeSet;
public class Person implements Comparable<Person> {
private String name;
private int age;
private double income;
private Book book;
public Person(String name, int age, double income, Book book) {
this.name = name;
this.age = age;
this.income = income;
this.book = book;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getIncome() {
return income;
}
public Book getBook() {
return book;
}
@Override
public int compareTo(Person o) {
// 先按照收入从高到低排序
int result = Double.compare(o.income, this.income);
if (result == 0) {
// 收入相等的情况下, 按照年龄从小到大排序
result = Integer.compare(this.age, o.age);
if (result == 0) {
// 如果收入和年龄都相等, 按照姓名排序
result = this.name.compareTo(o.name);
if (result == 0) {
// 如果以上3个属性都相等, 按照书排序
result = this.book.compareTo(o.book);
}
}
}
return result;
}
public static void main(String[] args) {
TreeSet<Person> set = new TreeSet<>();
Book book1 = new Book("Java编程思想", 99.9);
Book book2 = new Book("Java核心技术", 99.9);
Book book3 = new Book("Effective Java", 88.8);
Person person1 = new Person("Tom", 20, 10000, book1);
Person person2 = new Person("Bob", 25, 10000, book2);
Person person3 = new Person("Alice", 20, 10000, book3);
set.add(person1);
set.add(person2);
set.add(person3);
for (Person person : set) {
System.out.println(person.getName() + " " + person.getAge() + " " + person.getIncome() + " " + person.getBook().getName() + " " + person.getBook().getPrice());
}
}
}
```
Book类的定义如下:
```java
public class Book implements Comparable<Book> {
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
@Override
public int compareTo(Book o) {
// 先按照书价格从低到高排序
int result = Double.compare(this.price, o.price);
if (result == 0) {
// 如果书价格相等, 按照书名(字典顺序)
result = this.name.compareTo(o.name);
}
return result;
}
}
```
运行上面的代码,输出结果如下:
```
Bob 25 10000.0 Java核心技术 99.9
Alice 20 10000.0 Effective Java 88.8
Tom 20 10000.0 Java编程思想 99.9
```
阅读全文