老师帮忙看下代码,谢谢
//实现Comparable接口
public class Employee implements Comparable<Employee>{
//成员变量
private String number;
private String name;
private float salary;
//构造方法
public Employee(String number,String name,float salary){
super();
this.number=number;
this.name=name;
this.salary=salary;
}
//getter和setter方法
public String getNumber(){
return number;
}
public void setNumber(String number){
this.number=number;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public float getSalary(){
return salary;
}
public void setSalary(float salary){
this.salary=salary;
}
//toString()方法
public String toString(){
return "员工[编号:"+this.getNumber()+",姓名:"+this.getName()+",工资:"+this.getSalary();
}
public int compareTo(Employee e1){
float salary1=this.getSalary();
float salary2=e1.getSalary();
int n=new Float(salary2-salary1).intValue();
return n;
}
}
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class EmployeeTest{
public static void main(String[] args){
//定义Employee类的对象
Employee e1=new Employee("emp001","张三",1800.0f);
Employee e2=new Employee("emp002","李四",2500.0f);
Employee e3=new Employee("emp003","王五",1600.0f);
//将对象添加到List中
List<Employee> list=new ArrayList<Employee>();
list.add(e1);
list.add(e2);
list.add(e3);
//输出排序前的数据
System.out.println("排序前:");
for(Employee i:list){
System.out.println(i);
}
//排序
Collections.sort(list);
//输出排序后的数据
System.out.println("排序后:");
for(Employee i:list){
System.out.println(i);
}
}
}
正在回答 回答被采纳积分+1
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星