Java类排序
public class Student implements Comparable<Student>{ private String name = null; private int age = 0; 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; } public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return String.format("Name=%s Age=%d", this.name, this.age); } @Override public int compareTo(Student o) { // 按名字排序 return this.name.compareTo(o.getName()); } }
声明一个Student数组,并且调用Arrays.sort()进行排序,然后输出
Student[] stus = new Student[3]; stus[0] = new Student("Flowers", 12); stus[1] = new Student("Boys", 13); stus[2] = new Student("Zero", 21); Arrays.sort(stus); for(Student s : stus){ System.out.println(s.toString()); }
结果:
Name=Boys Age=13
Name=Flowers Age=12
Name=Zero Age=21
方法二,如果Student类并未实现Comparable<T>接口,则在调用Arrays.sort()时,要指定一个“比较器”,一个接口类Comparator<T>,所以使用时同时要写出实现intcompare(T o1, T o2);方法的代码。调用代码如下:
Arrays.sort(stus, new Comparator<Student>(){ @Override public int compare(Student o1, Student o2) { return o1.getName().compareTo(o2.getName()); } } }
对于集合的排列,如ArrayList等实现了Collection<T>接口,List<T>是继承于Collection<T>,所以实现List<T>的同样适用。集合类的排序主要是用Collections.sort方法,Collections和Collection是不一样的,前者是类,后者是接口。
一般我们主要使用两个方法:
1.Collection.sort(List arg0);
这种是最简单的一种排序方法,只需要实现他的Comparable 接口及实现public int compareTo(Object arg0)方法即可。
ArrayList<Student> list = newArrayList<Student>(3); list.add(new Student("Flowers", 36)); list.add(new Student("Dog", 23)); list.add(new Student("About", 67)); Collections.sort(list);
2.Collection.sort(List arg0,Comparator arg1)
这种加入了比较器,具有更大的灵活性,便于管理,比较器可作为内部静态类的,以便于管理。比较器必须实现Comparator接口。
Collections.sort(list, new Comparator<Student>(){ @Override public int compare(Student o1, Student o2) { // 按年龄排序 return o1.getAge() > o2.getAge()? 1:(o1.getAge() ==o2.getAge()? 0: -1); } });
以上两种方法,得到的结果都一样:
Name=Dog Age=23
Name=Flowers Age=36
Name=About Age=67
查看Collection.sort的源代码,不难看出Java的思路,先讲集合类转化为数组,然后调用Arrays.sort方法进行排序,同时传递过去比较器,最后利用集合的迭代器将结果赋值回集合类中。
public static <T> void sort(List<T> list, Comparator<? super T> c) { Object[] a = list.toArray(); Arrays.sort(a, (Comparator)c); ListIterator i = list.listIterator(); for (int j=0; j<a.length; j++) { i.next(); i.set(a[j]); } }
温馨提示:文章内容系作者个人观点,不代表Lan's Blog对观点赞同或支持。
版权声明:本文为转载文章,来源于 返回主页一沙鸥 ,版权归原作者所有,欢迎分享本文,转载请保留出处!
发表评论