老师帮忙看一下哪里有问题

来源:4-4 编程练习

dddddda

2020-09-29 18:25:26

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);
        
        //输出排序前的数据
        
        
        //排序
        Collections.sort(list);
        for(Employee em:list){
            System.out.println(em);
        }
        
        //输出排序后的数据
        
    }
}


//实现Comparable接口
public class Employee {
    //成员变量
    
    
    //构造方法
    
    
    //getter和setter方法
    
    
    //toString()方法
    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;
	}

	public String toString() {
		return "员工[编号:" + id + ", 姓名:" + name + ", 工资:" + salary
				+ "]";
	}

    public int comparaTo(Employee o){
        float s1 = this.getSalary();
        float s2 = o.getSalary();
        int n = (int)(s1-s2);
        return n;
    }
}


写回答

1回答

好帮手慕小脸

2020-09-29

同学你好,这里是因为同学没有在实体类中实现Comparable接口,所以sort方法那会出现报错。修改代码如下所示:

http://img.mukewang.com/climg/5f730e5e09298c6806360185.jpg

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

0

0 学习 · 16556 问题

查看课程