1.List对象实现Comparable接口,使对象具备可比性
package tao; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; public class Student1 implements Comparable<Student1> {
private String name;
private Integer age;
public Student1(String name, Integer age) {
super();
this.name = name;
this.age = 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;
}
@Override
public int compareTo(Student1 o) {
// TODO Auto-generated method stub
return this.getAge().compareTo(o.getAge());
} // 测试方法
public static void main(String[] args) {
List<Student1> list = new ArrayList<Student1>(); Student1 s1 = new Student1("lisi1",);
Student1 s2 = new Student1("lisi3",);
Student1 s3 = new Student1("lisi2",); list.add(s1);
list.add(s2);
list.add(s3); Collections.sort(list); for(Student1 s : list){
System.out.println("name:"+s.getName()+" age:"+s.getAge());
}
}
}
排序结果
name:lisi3 age:
name:lisi1 age:
name:lisi2 age:
2.List对象不具备可比性,或者对象本身可比性不是想要的排序规则,通过Comparator外部比较
package tao; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; public class Student2 {
private String name;
private Integer age;
public Student2(String name, Integer age) {
super();
this.name = name;
this.age = 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 static void main(String[] args) {
List<Student2> list = new ArrayList<Student2>(); Student2 s1 = new Student2("lisi1",);
Student2 s2 = new Student2("lisi3",);
Student2 s3 = new Student2("lisi2",); list.add(s1);
list.add(s2);
list.add(s3); Collections.sort(list,new MyCompare()); for(Student2 s : list){
System.out.println("name:"+s.getName()+" age:"+s.getAge());
}
}
} class MyCompare implements Comparator<Object> { @Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Student2 s1 = (Student2)o1;
Student2 s2 = (Student2)o2;
return s1.getAge().compareTo(s2.getAge());
}
}
排序结果
name:lisi3 age:
name:lisi1 age:
name:lisi2 age:
3.Comparable和Compartor的区别
a.出处不同
java.util.Comparator;
java.lang.Comparable;
b.提供方法不同
Comparator提供int compare(Object o1, Object o2)
Comparable提供int compareTo(Object o)
c.内外部区别
Comparator提供外部对比
Comparable提供对象自身对比