老师,我的代码有问题吗?特别是compareTo方法

来源:4-4 编程练习

谁叫我这么坏

2020-10-13 15:57:08

//实现Comparable接口
public class Employee implements Comparable<Employee> {

	@Override
	public int compareTo(Employee arg0) {
		int n = (int) (arg0.getMoney() - this.getMoney());
		return n;
	}

	// 成员变量
	private String id;
	private String name;
	private float money;

	// 构造方法
	public Employee() {

	}

	public Employee(String id, String name, float money) {
		this.setId(id);
		this.setName(name);
		this.setMoney(money);
	}

	// getter和setter方法
	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 getMoney() {
		return money;
	}

	public void setMoney(float money) {
		this.money = money;
	}

	// toString()方法
	@Override
	public String toString() {
		return "员工 [编号" + id + ", 姓名" + name + ", 工资" + money + "]";
	}

}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class EmployeeTest {

	public static void main(String[] args) {
		// 定义Employee类的对象
		Employee emp1 = new Employee("emp001", "张三", 1800.0f);
		Employee emp2 = new Employee("emp002", "李四", 2500.0f);
		Employee emp3 = new Employee("emp003", "王五", 1600.0f);

		// 将对象添加到List中
		List<Employee> list = new ArrayList<Employee>();
		list.add(emp1);
		list.add(emp2);
		list.add(emp3);
		// 输出排序前的数据
		System.out.println("排序前的数据为:");
		for (Employee emp : list) {
			System.out.println(emp);
		}
		System.out.println("******************************");
		// 排序
		Collections.sort(list);

		// 输出排序后的数据
		System.out.println("排序后的数据为:");
		for (Employee emp : list) {
			System.out.println(emp);
		}
	}
}


写回答

1回答

好帮手慕小班

2020-10-13

同学你好,同学已完成练习,没有问题。不错哟,继续加油!!

如果我的回答解决了你的疑惑,请采纳,祝学习愉快~

0

0 学习 · 16556 问题

查看课程