建一个员工类 继承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());
}
}
}