今天上课,老师讲到Arrays.sor()的时候说,这个可以对数组进行排序,于是当时脑海中立刻浮现出两个问题:一、如果对类排序,一定要把实现什么接口。二、实现了这个接口,Java怎么知道一个类是否实现了某个接口。于是带着这个问题做了一翻查找。
对于类数组排序,调用Arrays.sort()即可,但是也只是对于基本类型的支持,如果对类进行排序,有如下两种方法:
方法一,该类一定要实现Comparable接口,并且实现public int compareTo(T o);方法。比较结果大的返回1,相等返回0,小于返回-1。该接口实现了泛型,如果声明,则compareTo的参数则为Object。
实体类Student:
1 publicclassStudentimplementsComparable{2 privateString name=null;3 privateintage=0;4 publicString getName() {5 returnname;6 }7 publicvoidsetName(String name) {8 this.name=name;9 }10 publicintgetAge() {11 returnage;12 }13 publicvoidsetAge(intage) {14 this.age=age;15 }16 publicStudent(String name,intage) {17 this.name=name;18 this.age=age;19 }20 @Override21 publicString toString() {22 returnString.format("Name=%s Age=%d",this.name,this.age);23 }24 @Override25 publicintcompareTo(Student o) {26 //按名字排序27 returnthis.name.compareTo(o.getName());28 }29 }
声明一个Student数组,并且调用Arrays.sort()进行排序,然后输出
1 Student[] stus=newStudent[3];2 stus[0]=newStudent("Flowers",12);3 stus[1]=newStudent("Boys",13);4 stus[2]=newStudent("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接口,则在调用Arrays.sort()时,要指定一个“比较器”,一个接口类Comparator,所以使用时同时要写出实现intcompare(T o1, T o2);方法的代码。调用代码如下:
1 Arrays.sort(stus,newComparator(){2 @Override3 publicintcompare(Student o1, Student o2) {4 returno1.getName().compareTo(o2.getName());5 }6 });
对于集合的排列,如ArrayList等实现了Collection接口,List是继承于Collection,所以实现List的同样适用。集合类的排序主要是用Collections.sort方法,Collections和Collection是不一样的,前者是类,后者是接口。
一般我们主要使用两个方法:
1.Collection.sort(List arg0);
这种是最简单的一种排序方法,只需要实现他的Comparable 接口及实现public int compareTo(Object arg0)方法即可。
1 ArrayListlist=newArrayList(3);2 list.add(newStudent("Flowers",36));3 list.add(newStudent("Dog",23));4 list.add(newStudent("About",67));5 Collections.sort(list);
2.Collection.sort(List arg0,Comparator arg1)
这种加入了比较器,具有更大的灵活性,便于管理,比较器可作为内部静态类的,以便于管理。比较器必须实现Comparator接口。
1 Collections.sort(list,newComparator(){2 @Override3 publicintcompare(Student o1, Student o2) {4 //按年龄排序5 returno1.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 publicstaticvoidsort(Listlist, Comparator<?superT>c) {2 Object[] a=list.toArray();3 Arrays.sort(a, (Comparator)c);4 ListIterator i=list.listIterator();5 for(intj=0; j