定义一个 Person 类。 属性有: 姓名、 收入、 年龄、 书(一本)。 定义一个 Book 类; 属性有: 书名、 价格。 要求用 Comparable 接口实现, 使用 TreeSet<Person>集合存储, 排序规则:
时间: 2024-05-12 12:13:50 浏览: 81
根据收入从高到低排序,如果收入相同则按照年龄从小到大排序。
以下是示例代码:
```java
import java.util.*;
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 other) {
if (this.income != other.income) {
return other.income - this.income;
} else {
return this.age - other.age;
}
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", income=" + income +
", age=" + age +
", book=" + book +
'}';
}
}
class 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 String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
public class Main {
public static void main(String[] args) {
Book book1 = new Book("Java编程思想", 99.9);
Book book2 = new Book("Java核心技术", 88.8);
Book book3 = new Book("Effective Java", 66.6);
Person person1 = new Person("Tom", 100000, 30, book1);
Person person2 = new Person("Jerry", 80000, 25, book2);
Person person3 = new Person("Bob", 90000, 35, book3);
TreeSet<Person> set = new TreeSet<>();
set.add(person1);
set.add(person2);
set.add(person3);
for (Person person : set) {
System.out.println(person);
}
}
}
```
输出结果为:
```
Person{name='Tom', income=100000, age=30, book=Book{name='Java编程思想', price=99.9}}
Person{name='Bob', income=90000, age=35, book=Book{name='Effective Java', price=66.6}}
Person{name='Jerry', income=80000, age=25, book=Book{name='Java核心技术', price=88.8}}
```
阅读全文