1、Comparable接口实现排序,请参考下列代码
public class HelloWorld {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
TreeSet<Student> set = new TreeSet<Student>();
for (int i = 9; i >= 0; i--) {
list.add(new Student("list" + i, i));
set.add(new Student("set" + i, i));
}
// ArrayList需要手动调用Collections.sort(list)进行排序,TreeSet实现Comparable接口会自动排序(但是HashSet不能像TreeSet这样排序,他的排序可以转成ArrayList或者TreeSet实现排序)
Collections.sort(list);
showCollection(list);
showCollection(set);
}
public static void showCollection(Collection<Student> c) {
System.out.println();
for (Student s : c) {
System.out.printf("%s ", s.getAge());
}
}
}
class Student implements Comparable<Student> {
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = 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(Student s) {
if (s == null) {
return -1;
}
int age2 = s.getAge();
if (age > age2) {
return 1;
} else if (age == age2) {
return 0;
} else {
return -1;
}
}
}
2、Comparator接口进行排序,请参考下列代码
public class HelloWorld {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
TreeSet<Student> set = new TreeSet<Student>(myComparator);
for (int i = 9; i >= 0; i--) {
list.add(new Student("list" + i, i));
set.add(new Student("set" + i, i));
}
Collections.sort(list, myComparator);
showCollection(list);
showCollection(set);
}
private static Comparator<Student> myComparator = new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
if (s1 == null || s2 == null) {
return -1;
}
int age1 = s1.getAge();
int age2 = s2.getAge();
if (age1 > age2) {
return 1;
} else if (age1 == age2) {
return 0;
} else {
return -1;
}
}
};
public static void showCollection(Collection<Student> c) {
System.out.println();
for (Student s : c) {
System.out.printf("%s ", s.getAge());
}
}
}
class Student {
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = 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;
}
}
3、总结
简单粗暴的理解:Comparable和Comparator两者完成的事情是一样的,都是对集合按照指定的排序规则进行排序,前者比较固定,和一个具体类相绑定,而后者比较灵活,它可以被用于各个需要比较的集合中。可以说前者属于 “静态绑定”,而后者可以 “动态绑定”。