java中,如何利用现有数据结构对对象数组Arrays进行排序?
利用Arryas.sort()方法排序,需要结合有两种常用方法:1.使用Comparable接口;2.使用Comparator接口;
假设需要对一个Employee数组进行排序,按薪水高低排序,薪水较小的排在前,较大排在后.
使用Comparable
public class Employee implements Comparable<Employee> {
private String name;
private double salary;
public Employee (String name, double salary) {
this.name = name;
this.salary = salary;
}
public int getSalary(){
return salary;
}
public int getName() {
retunr name;
}
@override
public int compareTo(Employee other) {
return Double.compare(e.getSalary(), other.getSalary());
}
}
静态函数Arrays.sort()是对数组对象进行快速排序,要求对象必须实现了Comparable接口,而且元素之间比较是通过compareTo进行。
当进行x.compareTo(y)时,如果y是x子类则没有问题,而如果y是x父类,则会出现异常。
public class EmployeeTest{
public void main(String[] argv) {
// create data source
Employee[] employees = new Employee[3];
employees[0] = new Employee("henrry", 15000);
employees[1] = new Employee("jok", 20000);
employees[2] = new Employee("martin", 13000);
Arrays.sort(employees); // sort
for (Employee e : employees) { // check result
System.out.println("name = " + e.getName() + ", salary = " + e.getSalary());
}
}
}
运行输出
name = martin, salary = 13000.0
name = henrry, salary = 15000.0
name = jok, salary = 20000.0
还是跟Comparable一样的需求例子,不过实现会有差异。待排序类Employee不再实现Comparable或者Comparator接口。
public class Employee {
private String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}
public class EmployeeComparator implments Comparator<Employee> {
@Override
public int compareTo(Employee e1, Employee e2) {
return return Double.compare(e1.getSalary() , e2.getSalary());
}
}
public class EmployeeComparatorTest {
public void main(String [] argvs) {
// create data source
Employee[] employees = new Employee[3];
employees[0] = new Employee("henrry", 15000);
employees[1] = new Employee("jok", 20000);
employees[2] = new Employee("martin", 13000);
Arrays.sort(employees, new EmployeeComparator()); // sort
for (Employee e : employees) { // check result
System.out.println("name = " + e.getName() + ", salary = " + e.getSalary());
}
}
}
运行结果(与Comparable的例子一样))
name = martin, salary = 13000.0
name = henrry, salary = 15000.0
name = jok, salary = 20000.0
注意:
x.compareTo(y)会将y转换成x的同类型进行比较,也就是说如果x是y的基类,则没有问题;
如果反过来,y.compareTo(x),x还是y的基类就会出现异常,因为会先将x转换成y的同类型;
java> Comparable接口和Comparator接口
原文:https://www.cnblogs.com/fortunely/p/13722026.html