定义一个Person类。属性有: 定义一个Book类; 属性有: 书名、 价格。 要求用Comparable接口实现, 使用TreeSet<Person>集合存储, 排序规则: A.先按照收入从高到低排序; B.收入相等的情况下, 按照年龄从小到大排序; C.如果收入和年龄都相等, 按照姓名排序, 字典顺序(String类的compareTo方法); D.如果以上3个属性都相等, 按照书排序, 先按照书价格从低到高, 如果书价格相等, 按照书名(字典顺序)利用自定义比较器Comparator实现类
时间: 2023-06-24 07:08:21 浏览: 102
TreeSet类-java容器类
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;
}
@Override
public int compareTo(Person o) {
if (this.income != o.income) {
return Double.compare(o.income, this.income);
} else if (this.age != o.age) {
return Integer.compare(this.age, o.age);
} else if (!this.name.equals(o.name)) {
return this.name.compareTo(o.name);
} else {
return this.book.compareTo(o.book);
}
}
public static void main(String[] args) {
TreeSet<Person> set = new TreeSet<>();
set.add(new Person("Tom", 20, 1000.0, new Book("Java", 20)));
set.add(new Person("Jerry", 30, 1000.0, new Book("Python", 10)));
set.add(new Person("Alice", 20, 2000.0, new Book("C++", 20)));
set.add(new Person("Bob", 30, 1000.0, new Book("JavaScript", 20)));
for (Person p : set) {
System.out.println(p.name + " " + p.age + " " + p.income + " " + p.book.name + " " + p.book.price);
}
}
}
```
Book类的定义如下:
```java
public class Book implements Comparable<Book> {
private String name;
private int price;
public Book(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public int compareTo(Book o) {
if (this.price != o.price) {
return Integer.compare(this.price, o.price);
} else {
return this.name.compareTo(o.name);
}
}
}
```
在Person类中实现了Comparable接口,重写了compareTo方法,按照题目要求进行排序。Book类也实现了Comparable接口,重写了compareTo方法,用于在Person类中按照书的价格和书名进行排序。
在main方法中,创建了一个TreeSet集合,并向其中添加了4个Person对象。按照题目要求进行了排序,并打印输出了结果。
阅读全文