4-4编程练习
import java.util.ArrayList;
import java.util.Collections;
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中
ArrayList<Employee> list = new ArrayList<Employee>();
list.add(e1);
list.add(e2);
list.add(e3);
//输出排序前的数据
System.out.println("按名字排序前:");
for (Employee e : list) {
System.out.println(e);
}
//排序
Collections.sort(list);
//输出排序后的数据
System.out.println("按名字排序后:");
for (Employee e : list) {
System.out.println(e);
}
}
}public class Employee implements Comparable<Employee>{
private String id;
private String name;
private float salary;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
public Employee() {
}
public Employee(String id, String name, float salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "员工[编号:" + id + ", 姓名:" + name + ", 工资:" + salary
+ "]";
}
@Override
public int compareTo(Employee o) {
float f1 = this.getSalary();
float f2 = o.getSalary();
int n = (int)(f2-f1);
return n;
}
}78
收起
正在回答
1回答
同学你好,已完成练习,不错哟,继续加油!!
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
相似问题
登录后可查看更多问答,登录/注册
java工程师2020版
- 参与学习 人
- 提交作业 9410 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星