使用集合存储员工对象,按照年龄降序排序,如果年龄相等按照薪资降序排序,如果薪资相等按照姓名的哈希码值降序排序。

建一个员工类 继承Comparaple 


public class Employee implements Comparable<Employee> {

	private String name;
	private int age;
	private double salary;

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

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

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

	public Employee() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public int compareTo(Employee o) {// 那当前 员工对象和外来员工对象进行比较 (自然顺序比较是小的在前大的在后)
		if (this.getAge() > o.getAge()) {
			return -1;// this-o小于0,表示this在前 o在后
		} else if (this.getAge() == o.getAge()) {

			if (this.getSalary() > o.getSalary()) {
				return -1;
			} else if (this.getSalary() == o.getSalary()) {
				if (this.getName().hashCode() > o.getName().hashCode()) {
					return -1;// 返回小于0的值,当前对象在前,外来对象在后
				} else if (this.getName().hashCode() == o.getName().hashCode()) {
					return 0;// 同一个对象
				} else {
					return 1;
				}
			} else {
				return 1;// 返回大于0的值,当前对象在后,外来对象在前
			}
		} else {
			return 1;// this-o大于0,表示this在后 o在前
		}

	}

}

测试类Demo

package com.zhiyou.wch3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

public class Demo {
	public static void main(String[] args) {

		TreeSet<Employee> treeSet = new TreeSet<>();
		Employee employee = new Employee("小明", 20, 2000);
		Employee employee1 = new Employee("小张", 27, 2000);
		Employee employee2 = new Employee("小红", 30, 2000);
		Employee employee3 = new Employee("小李", 20, 2000);
		Employee employee4 = new Employee("小明", 20, 2000);
		Employee employee5 = new Employee("小明", 25, 2000);
		Employee employee6 = new Employee("小明", 20, 4000);
		treeSet.add(employee6);
		treeSet.add(employee5);
		treeSet.add(employee4);
		treeSet.add(employee3);
		treeSet.add(employee2);
		treeSet.add(employee1);
		treeSet.add(employee);
		Iterator<Employee> iterator = treeSet.iterator();
		while (iterator.hasNext()) {
			Employee emp = iterator.next();
			System.out.println(emp.getAge() + "\t" + emp.getSalary() + "\t" + emp.getName().hashCode());
		}

	}

}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值