Java类排序

      今天上课,老师讲到Arrays.sor()的时候说,这个可以对数组进行排序,于是当时脑海中立刻浮现出两个问题:一、如果对类排序,一定要把实现什么接口。二、实现了这个接口,Java怎么知道一个类是否实现了某个接口。于是带着这个问题做了一翻查找。

      对于类数组排序,调用Arrays.sort()即可,但是也只是对于基本类型的支持,如果对类进行排序,有如下两种方法:

      方法一,该类一定要实现Comparable<T>接口,并且实现public int compareTo(T o);方法。比较结果大的返回1,相等返回0,小于返回-1。该接口实现了泛型,如果声明,则compareTo的参数则为Object。

实体类Student:

1 public class Student implements Comparable<Student>{
2 private String name = null;
3 private int age = 0;
4 public String getName() {
5 return name;
6 }
7 public void setName(String name) {
8 this.name = name;
9 }
10 public int getAge() {
11 return age;
12 }
13 public void setAge(int age) {
14 this.age = age;
15 }
16 public Student(String name, int age) {
17 this.name = name;
18 this.age = age;
19 }
20 @Override
21 public String toString() {
22 return String.format("Name=%s Age=%d", this.name, this.age);
23 }
24 @Override
25 public int compareTo(Student o) {
26 // 按名字排序
27   return this.name.compareTo(o.getName());
28 }
29 }

声明一个Student数组,并且调用Arrays.sort()进行排序,然后输出

1 Student[] stus = new Student[3];
2 stus[0] = new Student("Flowers", 12);
3 stus[1] = new Student("Boys", 13);
4 stus[2] = new Student("Zero", 21);
5 Arrays.sort(stus);
6  for(Student s : stus){
7 System.out.println(s.toString());
8 }

结果:

Name=Boys Age=13

Name=Flowers Age=12

Name=Zero Age=21

 

       方法二,如果Student类并未实现Comparable<T>接口,则在调用Arrays.sort()时,要指定一个“比较器”,一个接口类Comparator<T>,所以使用时同时要写出实现intcompare(T o1, T o2);方法的代码。调用代码如下:

1 Arrays.sort(stus, new Comparator<Student>(){
2 @Override
3 public int compare(Student o1, Student o2) {
4 return o1.getName().compareTo(o2.getName());
5 }
6 });

     对于集合的排列,如ArrayList等实现了Collection<T>接口,List<T>是继承于Collection<T>,所以实现List<T>的同样适用。集合类的排序主要是用Collections.sort方法,Collections和Collection是不一样的,前者是类,后者是接口。

一般我们主要使用两个方法:

     1.Collection.sort(List arg0);

 这种是最简单的一种排序方法,只需要实现他的Comparable 接口及实现public int compareTo(Object arg0)方法即可。

1 ArrayList<Student> list = newArrayList<Student>(3);
2 list.add(new Student("Flowers", 36));
3 list.add(new Student("Dog", 23));
4 list.add(new Student("About", 67));
5 Collections.sort(list);

 

    2.Collection.sort(List arg0,Comparator arg1)

 这种加入了比较器,具有更大的灵活性,便于管理,比较器可作为内部静态类的,以便于管理。比较器必须实现Comparator接口。

1 Collections.sort(list, new Comparator<Student>(){
2 @Override
3 public int compare(Student o1, Student o2) {
4 // 按年龄排序
5   return o1.getAge() > o2.getAge()? 1:(o1.getAge() ==o2.getAge()? 0: -1);
6 }
7 });

 以上两种方法,得到的结果都一样:

Name=Dog Age=23

Name=Flowers Age=36

Name=About Age=67

 

      查看Collection.sort的源代码,不难看出Java的思路,先讲集合类转化为数组,然后调用Arrays.sort方法进行排序,同时传递过去比较器,最后利用集合的迭代器将结果赋值回集合类中。

1 public static <T> void sort(List<T> list, Comparator<? super T> c) {
2 Object[] a = list.toArray();
3 Arrays.sort(a, (Comparator)c);
4 ListIterator i = list.listIterator();
5 for (int j=0; j<a.length; j++) {
6 i.next();
7 i.set(a[j]);
8 }
9 }

posted @ 2010-09-29 12:51  一沙鸥  阅读(4123)  评论(0编辑  收藏  举报