解释这些代码import java.util.TreeSet;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 employee) { return Integer.compare(this.id, employee.id); } @Override public String toString() { return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", salary=" + salary + '}'; } public static void main(String[] args) { TreeSet<Employee> employees = new TreeSet<>(); employees.add(new Employee(2, "Tom", 5000)); employees.add(new Employee(1, "Jerry", 6000)); employees.add(new Employee(3, "Bob", 4000)); System.out.println(employees); }}
时间: 2024-02-14 08:35:38 浏览: 69
java代码-import java.util.Scanner;
5星 · 资源好评率100%
这段代码定义了一个名为 Employee 的类,该类实现了 Comparable 接口,并重写了 compareTo 方法,以便在 TreeSet 中进行比较和排序。Employee 类有三个属性:id、name 和 salary,以及一个构造函数和三个 getter 方法。在 main 方法中,使用 TreeSet 对象 employees 存储了三个 Employee 对象,并打印输出了它们。由于 Employee 实现了 Comparable 接口,TreeSet 可以按照 id 属性值的大小将 Employee 对象进行排序,并输出排序后的结果。输出结果为:[Employee{id=1, name='Jerry', salary=6000.0}, Employee{id=2, name='Tom', salary=5000.0}, Employee{id=3, name='Bob', salary=4000.0}]。
阅读全文