Comparable 4-4编程

来源:4-4 编程练习

rock221

2021-01-19 15:48:05

//实现Comparable接口

public class Employee implements Comparable<Employee>{

    //成员变量

    private String number;

    private String name;

    private double salary;

    

    

    //构造方法

    public Employee(String number,String name,double salary){

        this.setNumber(number);

        this.setName(name);

        this.setSalary(salary);

    }

    

    

    //getter和setter方法

    public void setNumber(String number){

        this.number=number;

    }

    

    public String getNumber(){

        return number;

    }

    public void setName(String name){

        this.name=name;

    }

    public String getName(){

        return name;

    }

    public void setSalary(double salary){

        this.salary=salary;

        

    }

    public double getSalary(){

        return salary;

    }

    //toString()方法

    public String toString(){

        return "员工[编号:"+this.getNumber()+",姓名:"+this.getName()+",工资:"+this.getSalary()+"]";

    }

    public int compareTo(Employee o){

        double salary1=this.getSalary();

        double salary2=o.getSalary();

     int n=  new Double(salary2-salary1).intValue();

     return n;

    }

}

import java.util.ArrayList;

import java.util.Collections;

import java.util.Iterator;

import java.util.List;


public class EmployeeTest{

    

    

    

    public static void main(String[] args){

        //定义Employee类的对象

        Employee e1=new Employee("emp001","张三",1800.0);

        Employee e2=new Employee("emp002","张三",2500.0);

        Employee e3=new Employee("emp003","张三",1600.0);

        

        

        //将对象添加到List中

        List <Employee> employeeList=new ArrayList<Employee>();

        employeeList.add(e1);

        employeeList.add(e2);

        employeeList.add(e3);

        

        

        //输出排序前的数据

        System.out.println("排序前:");

        Iterator<Employee> it=employeeList.iterator();

        while(it.hasNext()){

            System.out.println(it.next());

        }

        

        

        

        //排序

        Collections.sort(employeeList);

        

        //输出排序后的数据

        System.out.println("排序后:");

        for(Employee test:employeeList){

            System.out.println(test);

        }

        

    }

}


写回答

1回答

好帮手慕阿园

2021-01-19

同学你好,已完成练习,不错哟,继续加油!!

祝学习愉快~


0

0 学习 · 16556 问题

查看课程

相似问题

回答 1

4-4编程练习

回答 1

回答 2