java 中的2个接口 Comparable和Comparator
像Integer、String这些类型的数据都是已经实现Comparable接口的,所以对这些类型可以直接通过Arrays.sort(...)和Collections.sort(...)方法进行排序。但是对于一些自己new出来的对象而言,如果想使用sort这种方法,必须要实现Comparable接口,这是由sort方法底层决定的,具体看一下实例:
定义一个Bean
public class Employee implements Comparable{
private int age; private String name;
public Employee(String name,int age){
this.name=name;
this.age=age;
} public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result; }
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override public String toString() {
return "Employee [age=" + age + ", name=" + name + "]";
}
@Override
public int compareTo(Object o) {
if(o instanceof Employee){
if(age > ((Employee) o).age){
return 1;
}else if(age == ((Employee) o).age){
return 0; }else if (age < ((Employee) o).age){
return -1; }
} return 0;
}
}
//
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class EmployeeSortTest {
public static void main(String[] args){
Employee[] staff = new Employee[3];
staff[0]= new Employee("aaa",12);
staff[1] = new Employee("bbb",13);
staff[2] = new Employee("ccc",14);
Arrays.sort(staff);//sort方法可以实现对对象数组的排序,但必须实现Comparable接口
for(Employee e: staff){
System.out.println(e);
} //以上方法虽然可以实现对象的排序,但是有弊端;
//1、修改了公共类Employee,而很多情况下我们是没有办法修改公共的类,
//2、当我们需求满足不同的方式进行排序时,这种方法是不可行的
//接下来java中提供了Comparator接口,Comparator使用其compare()方法返回的整数来比较2个对象,
//这样就无需修改公共类
System.out.println("---------------");
List<Employee> list = new ArrayList<Employee> ();
list.add(new Employee("aaa",12));
list.add(new Employee("bbb",13));
list.add(new Employee("bbb",14));
Collections.sort(list, new Comparator<Employee>(){
@Override
public int compare(Employee o1, Employee o2) {
// TODO Auto-generated method stub
return o1.getAge()-o2.getAge();
}
});
for(Employee e : list){
System.out.println(e);
}
}
}
//输出结果:
Employee [age=12, name=aaa]
Employee [age=13, name=bbb]
Employee [age=14, name=ccc]
Employee [age=12, name=aaa]
Employee [age=13, name=bbb]
Employee [age=14, name=bbb]