62,614
社区成员
发帖
与我相关
我的任务
分享
private
/**
* 覆写Comparable接口的方法
*
* 此方法用于对象的排序比较
*/
public int compareTo(Employee emp) {
if (this.salary > emp.salary) {
return 1;
} else if (this.salary < emp.salary) {
return -1;
} else {
return 0;
}
}
将上面的代码,1改为-1,-1改为1
public class Employee implements Comparable<Employee> {
private String name;
private int salary;
public Employee() {
}
public Employee(String name,int salary) {
this.name = name;
this.salary = salary;
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
* 覆写Comparable接口的方法
*/
@Override
public int compareTo(Employee o) {
return salary - o.getSalary();
}
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;
}
}
测试类
import java.util.Set;
import java.util.TreeSet;
public class EmployeeTest {
public static void main(String[] args) {
Set<Employee> emps = new TreeSet<Employee>();
emps.add(new Employee("张三", 8000));
emps.add(new Employee("李四", 6000));
emps.add(new Employee("王五", 5600));
emps.add(new Employee("马六", 7600));
for (Employee emp : emps) {
System.out.println(emp.getName() + ":" + emp.getSalary());
}
}
}
精髓就在compareTo上,compareTo的约定并没有指定返回值的大小,而只指定了返回值的符号。
package com.pyh.demo2;
public class Employee implements Comparable<Employee> {
private String name;
private double salary;
public Employee() {
}
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
/**
* 覆写Comparable接口的方法
*
* 此方法用于对象的排序比较
*/
public int compareTo(Employee emp) {
if (this.salary > emp.salary) {
return 1;
} else if (this.salary < emp.salary) {
return -1;
} else {
return 0;
}
}
}
package com.pyh.demo2;
import java.util.Set;
import java.util.TreeSet;
public class Demo10 {
public static void main(String[] args) {
Set<Employee> emps = new TreeSet<Employee>();
emps.add(new Employee("张三", 8000));
emps.add(new Employee("李四", 6000));
emps.add(new Employee("王五", 5600));
emps.add(new Employee("马六", 7600));
for (Employee emp : emps) {
System.out.println(emp.getName() + ":" + emp.getSalary());
}
}
}