假设Employee类包含一个int型成员id,一个 String型成员name,一个double型成员salar y。如果要求Employee可按id值比较大小,请编写Employee类。编写程序,创建几个Employee对象,将已们存放到TreeSet中并输出。
时间: 2024-03-14 11:46:26 浏览: 87
好的,以下是Employee类的实现代码:
```java
import java.util.Objects;
public class Employee implements Comparable<Employee> {
private int id;
private String name;
private double salary;
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
@Override
public int compareTo(Employee other) {
return Integer.compare(this.id, other.id);
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
Employee employee = (Employee) o;
return id == employee.id &&
Double.compare(employee.salary, salary) == 0 &&
Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name, salary);
}
}
```
其中,我们实现了Comparable接口,重写了compareTo方法,以便能够按照id值比较大小。
接下来,我们可以编写测试代码,创建几个Employee对象,将它们存放到TreeSet中并输出:
```java
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
Employee emp1 = new Employee(3, "Alice", 5000.0);
Employee emp2 = new Employee(1, "Bob", 6000.0);
Employee emp3 = new Employee(2, "Charlie", 7000.0);
Set<Employee> employees = new TreeSet<>();
employees.add(emp1);
employees.add(emp2);
employees.add(emp3);
for (Employee emp : employees) {
System.out.println(emp);
}
}
}
```
输出结果应该是:
```
Employee{id=1, name='Bob', salary=6000.0}
Employee{id=2, name='Charlie', salary=7000.0}
Employee{id=3, name='Alice', salary=5000.0}
```
阅读全文