1,Comparable的用法
package com.pojo;
/**
* Comparable<Object> 排序接口
*/
public class User implements Comparable<Object> {
private String name;
private int age;
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; }
@Override
public int compareTo(Object o) {
if(this==o){
return 0;
}else if(o!=null && o instanceof User){
User ob=(User)o;
if(age<=ob.getAge()){
return -1;
}else{
return 1;
}
}else{ return -1; }
}
}
测试类Comparable :
public class TestComparable {
public static void main(String[] args) {
List<User> list=new ArrayList<User>();
User us1=new User();
us1.setAge(10);
us1.setName("张三");
User us2=new User();
us2.setAge(20);
us2.setName("李四");
User us3=new User();
us3.setAge(30);
us3.setName("王五");
list.add(us1);
list.add(us3);
list.add(us2);
for(User u:list){
System.out.println("排序前顺序 :"+u.getName()+u.getAge());
}
Collections.sort(list);
for(User u:list){
System.out.println("排序后顺序 :"+u.getName()+u.getAge());
} } }
2,Comparator的用法
/**
* Comparator 比较器
*/
public class Person {
private String name;
private Integer age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; } }
/**
* 外部排序规则
*/
public class ageComparator implements Comparator<Object>{
/**
* 如果o1小于o2,返回一个负数;如果o1大于o2,返回一个正数;如果他们相等,则返回0;
*/
public int compare(Object o1, Object o2) {
if(o1 instanceof Person &&o2 instanceof Person){
Person ob1=(Person)o1;
Person ob2=(Person)o2;
return ob1.getAge()-ob2.getAge();
}else{
return 0;
} } }
测试类 Comarator:
public static void main(String[] args) {
List<Person> list=new ArrayList<Person>();
Person us1=new Person();
us1.setAge(10);
us1.setName("张");
Person us2=new Person();
us2.setAge(20);
us2.setName("李");
Person us3=new Person();
us3.setAge(30);
us3.setName("王");
Person us4=new Person();
us4.setAge(40);
us4.setName("离");
list.add(us1);
list.add(us3);
list.add(us2);
list.add(us4);
for(Person u:list){
System.out.println("排序前顺序 :"+u.getName()+u.getAge());
}
ageComparator comparator=new ageComparator();
Collections.sort(list, comparator);
for(Person u:list){
System.out.println("排序后顺序 :"+u.getName()+u.getAge());
} } }
总结:前者是在内部声明比较规则,或者是在外部声明比较规则;