开发肯定会涉及到排序,在java中,普通的数值排序直接使用一系列的算法即可,如果是对象的复杂排序,则可以使用comparable和comparator两个接口来实现,他们两者的区别如下
1 comparable是java.lang包下面的,是使得对象本身即可排序,将对象实现该接口,实现compareTo方法即可,比较该对象本身和传递对象的顺序,通过指定的字段进行比较,如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。比较时,对象可以放在一个数组或者其他集合中,数组使用Arrays.sort(array),集合使用Collections.sort(list)。
2 comparator 是java.util包下面,指使用一个专用的比较器对对象进行比较,他是一个策略模式,对象本身不用实现任何方法和接口,在比较对象时,通过传入对应的比较策略进行比较。数组使用Arrays.sort(array,comparatorStrategy),集合使用Collections.sort(list,comparatorStrategy)。
eg:
public class Student implements Comparable<Student> {
private int age;
private String name;
private int sex;
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;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
@Override
public int compareTo(Student o) {
if (this.getAge() > o.getAge())
return 1;
else if (this.getAge() < o.getAge())
return -1;
else
return 0;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
return sb.append("姓名:").append(this.getName()).append("年龄:").append(age).append("性别:").append(this.getSex() >= 1 ? "男":"女").toString();
}
}
待排序的实体
年龄排序器
import java.util.Comparator;
public class AgeComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
if (o1.getAge() > o2.getAge())
return 1;
else if (o1.getAge() < o2.getAge())
return -1;
else
return 0;
}
}
测试类
public class TestMain {
public static List<Student> setStudent() {
List<Student> list = new ArrayList<Student>();
Student s1 = new Student();
s1.setAge(12);
s1.setName("zhangsan");
s1.setSex(1);
Student s2 = new Student();
s2.setAge(11);
s2.setName("lisi");
s2.setSex(1);
Student s3 = new Student();
s3.setAge(13);
s3.setName("wangwu");
s3.setSex(0);
Student s4 = new Student();
s4.setAge(19);
s4.setName("zhaoliu");
s4.setSex(0);
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
return list;
}
public static void comparableSort() {
List<Student> l = setStudent();
System.out.println("未排序");
for (Student student : l) {
System.out.println(student);
}
//Collections.sort(l);
System.out.println("已排序");
for (Student student : l) {
System.out.println(student);
}
}
public static void comparatorSort() {
List<Student> l = setStudent();
System.out.println("未排序");
for (Student student : l) {
System.out.println(student);
}
AgeComparator a = new AgeComparator();
Collections.sort(l, a);
System.out.println("已排序");
for (Student student : l) {
System.out.println(student);
}
}
public static void main(String[] args) {
comparatorSort();
}
}