欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

创建一个TreeSet对象,并在其中添加一些员工对象(Employee),其姓名和工资分别是:张三8000,李四6000,王五5600,马六7500.最后按照工资的大小,降序输出(提示:让Employ

程序员文章站 2022-03-06 18:35:22
创建一个TreeSet对象,并在其中添加一些员工对象(Employee),其姓名和工资分别是:张三8000,李四6000,王五5600,马六7500.最后按照工资的大小,降序输出(提示:让Employee对象实现Comparable接口)package ch007;import java.util.TreeSet;public class Employee implements Comparable{ private String name; pri...

创建一个TreeSet对象,并在其中添加一些员工对象(Employee),其姓名和工资分别是:张三8000,李四6000,王五5600,马六7500.最后按照工资的大小,降序输出(提示:让Employee对象实现Comparable接口)

package ch007;

import java.util.TreeSet;

public class Employee implements Comparable<Employee>{
    private String name;
    private int salary;

    public Employee(String name,int salary){
        this.name=name;
        this.salary=salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                '}';
    }

    public static void main(String[] args) {
        TreeSet<Employee> treeSet=new TreeSet<>();
        Employee employee1=new Employee("张三",8000);
        Employee employee2=new Employee("李四",6000);
        Employee employee3=new Employee("王五",5600);
        Employee employee4=new Employee("马六",7500);
        treeSet.add(employee1);
        treeSet.add(employee2);
        treeSet.add(employee3);
        treeSet.add(employee4);
        for(Employee employee:treeSet){
            System.out.println(employee.toString());
        }
    }

    @Override
    public int compareTo(Employee o) {
        return o.salary-this.salary;
    }
}

本文地址:https://blog.csdn.net/Happy_change/article/details/111915533