使用集合儲存員工物件,按照年齡降序排序,如果年齡相等按照薪資降序排序,如果薪資相等按照姓名的雜湊碼值降序排序。
阿新 • • 發佈:2018-12-25
建一個員工類 繼承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()); } } }