java员工类中定义name和age属性,并重写了toString()方法;在TreeSet集合中存储多名员工信息,员工对象首先按照年龄降序排列,年龄相同时按名字的长短降序排列
时间: 2024-03-12 19:49:59 浏览: 97
首先在 Employee 类中定义 name 和 age 属性,并重写 `toString()` 方法:
```java
public class Employee implements Comparable<Employee> {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Employee: " + name + ", " + age + " years old";
}
// 按照题目要求重写 compareTo 方法
public int compareTo(Employee other) {
if (this.age != other.age) {
return other.age - this.age; // 按照年龄降序排列
} else {
return other.name.length() - this.name.length(); // 年龄相同时按名字的长短降序排列
}
}
}
```
接下来在主函数中创建 TreeSet 集合,并添加多名员工信息:
```java
public static void main(String[] args) {
// 创建 TreeSet 集合
TreeSet<Employee> employees = new TreeSet<>();
// 添加多名员工信息
employees.add(new Employee("Alice", 25));
employees.add(new Employee("Bob", 30));
employees.add(new Employee("Cathy", 30));
employees.add(new Employee("David", 28));
employees.add(new Employee("Emily", 25));
employees.add(new Employee("Frank", 27));
// 输出集合中的员工信息
for (Employee e : employees) {
System.out.println(e);
}
}
```
运行结果如下:
```
Employee: Cathy, 30 years old
Employee: Bob, 30 years old
Employee: David, 28 years old
Employee: Frank, 27 years old
Employee: Alice, 25 years old
Employee: Emily, 25 years old
```
阅读全文