用java程序编写
创建一个TreeSet对象,并自其中添加一些员工对象,其姓名和工资分别为:张三1000,李四2000,王五3000,马六4000,最后按照工资的多少进行降序输出(让Emp...
创建一个TreeSet对象,并自其中添加一些员工对象,其姓名和工资分别为:张三 1000,李四 2000,王五 3000,马六 4000,最后按照工资的多少进行降序输出(让Employee对象实现Comparable接口)
展开
1个回答
展开全部
import java.util.*;
public class Employee implements Comparable<Employee>{
private String name;
private double salary;
public Employee(String name, double salary){
this.name = name;
this.salary = salary;
}
public int compareTo(Employee emp){
if(emp.salary > salary){
return 1;
}else if(emp.salary < salary){
return -1;
}else {
return 0;
}
}
public String toString(){
return String.format("Employee[name=%s, salary=%.2f]", name, salary);
}
public static void main(String[] args){
Employee[] emps = new Employee[]{
new Employee("张三", 1000),
new Employee("李四", 2000),
new Employee("王五", 3000),
new Employee("马六", 4000)
};
System.out.println("排序前:" + Arrays.toString(emps));
Arrays.sort(emps);
System.out.println("排序后:" + Arrays.toString(emps));
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询