标签:
参考文档:Java排序: Comparator vs Comparable 入门
java类经常面临排序问题,据我所知:java提供comparable和comparator两种比较方式:
1. comparable方法需要排序的类继承comparable接口,重写compareTo函数,但是只能实现一种对比方法(重写compareTo一次),例如:
类定义如下:
class Student implements Comparable<Student> { private String name; private String key; private float score; private int age; public Student(String key, String name, float score, int age) { this.key = key; this.name = name; this.score = score; this.age = age; } @Override /* public int compareTo(Student ano) { if (this.score < ano.score) return -1; if (this.score > ano.score) return 1; else { if (this.age > ano.age) return 1; if (this.age < ano.age) return -1; else return 0; }//else }//compareTo */ public int compareTo(Student ano){ return (int)(this.score - ano.score); } }
可以看到compareTo被我们重写,接下来我们可以运行排序,然后观察运行结果:
Student stus[] = {new Student("lee","9527",22,80) ,new Student("zhang","1839",23,83) ,new Student("zhao","1284",21,80)}; print(stus); Arrays.sort(stus); System.out.println("after sorted:"); print(stus);
运行结果如下:
Student{name=‘9527‘, key=‘lee‘, score=22.0, age=80} Student{name=‘1839‘, key=‘zhang‘, score=23.0, age=83} Student{name=‘1284‘, key=‘zhao‘, score=21.0, age=80} after sorted: Student{name=‘1284‘, key=‘zhao‘, score=21.0, age=80} Student{name=‘9527‘, key=‘lee‘, score=22.0, age=80} Student{name=‘1839‘, key=‘zhang‘, score=23.0, age=83}
扩展:对元素是自定义类的List进行排序,自定List定义如下:
public static List<Student> getStudents(){ List<Student> col = new ArrayList<Student>(); Random rand = new Random(); String valkey; int valAge, valScore; String valName; for (int i = 0; i < 10; i++) { valkey = UUID.randomUUID().toString(); valName = RandomStringUtils.random(10, 20, 110, true, true); valAge = rand.nextInt(80); valScore = rand.nextInt(80); col.add(new Student(valkey,valName, valAge, valScore)); } return col; }
通过Collections.sort(List)方法进行排序:
List<Student> grade = Student.getStudents(); Iterator<Student> iter = grade.iterator(); Collections.sort(grade); while(iter.hasNext()) { //iter.next(); System.out.println(iter.next().toString()); }
2. 有时候我们需要对多种关键字进行排序,那么我们需要通过实现java.util.Comparator来实现,我们可以对类Student任何字段进行排序。我们不需要改变类Student,类本身不用实现java.lang.Comparable或者是java.util.Comparator接口,代码如下:
class studSortByName implements Comparator<Student> { public int compare(Student st1, Student st2){ return st1.getName().compareTo(st2.getName()); } }
接下来我们通过排序进行测验,我们必须使用Collections.sort(List, Comparator)这个方法而不是Collections.sort(List)方法:
public class ClassSort { public static void main(String []args) { //Student stu1 = new Student("wen", 90, 17); //Student stu2 = new Student("mike", 90, 18); //System.out.print("res:" + stu1.compareTo(stu2)); List<Student> grade = Student.getStudents(); Iterator<Student> iter = grade.iterator(); //Collections.sort(grade); Collections.sort(grade,new StudSortByName()); while(iter.hasNext()) { //iter.next(); System.out.println(iter.next().toString()); } /*Student stus[] = {new Student("lee","9527",22,80) ,new Student("zhang","1839",23,83) ,new Student("zhao","1284",21,80)}; print(stus); Arrays.sort(stus); System.out.println("after sorted:"); print(stus); */ } public static void print(Student [] stus){ for (int i = 0; i < stus.length; i++) { System.out.println(stus[i].toString()); } } }
附注可执行代码如下:
package comparable; import java.util.*; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.builder.Diff; /** * Created by carl on 11/7/15. */ class Student implements Comparable<Student> { private String name; private String key; private float score; private int age; public Student(String key, String name, float score, int age) { this.key = key; this.name = name; this.score = score; this.age = age; } @Override /* public int compareTo(Student ano) { if (this.score < ano.score) return -1; if (this.score > ano.score) return 1; else { if (this.age > ano.age) return 1; if (this.age < ano.age) return -1; else return 0; }//else }//compareTo */ public int compareTo(Student ano){ return (int)(this.score - ano.score); } public static List<Student> getStudents(){ List<Student> col = new ArrayList<Student>(); Random rand = new Random(); String valkey; int valAge, valScore; String valName; for (int i = 0; i < 10; i++) { valkey = UUID.randomUUID().toString(); valName = RandomStringUtils.random(10, 20, 110, true, true); valAge = rand.nextInt(80); valScore = rand.nextInt(80); col.add(new Student(valkey,valName, valAge, valScore)); } return col; } public String getName(){ return name; } public float getScore() { return score; } public int getAge() { return age; } @Override public String toString() { return "Student{" + "name=‘" + name + ‘\‘‘ + ", key=‘" + key + ‘\‘‘ + ", score=" + score + ", age=" + age + ‘}‘; } }//Student class StudSortByName implements Comparator<Student> { public int compare(Student st1, Student st2){ return st1.getName().compareTo(st2.getName()); } } public class ClassSort { public static void main(String []args) { //Student stu1 = new Student("wen", 90, 17); //Student stu2 = new Student("mike", 90, 18); //System.out.print("res:" + stu1.compareTo(stu2)); List<Student> grade = Student.getStudents(); Iterator<Student> iter = grade.iterator(); //Collections.sort(grade); Collections.sort(grade,new StudSortByName()); while(iter.hasNext()) { //iter.next(); System.out.println(iter.next().toString()); } /*Student stus[] = {new Student("lee","9527",22,80) ,new Student("zhang","1839",23,83) ,new Student("zhao","1284",21,80)}; print(stus); Arrays.sort(stus); System.out.println("after sorted:"); print(stus); */ } public static void print(Student [] stus){ for (int i = 0; i < stus.length; i++) { System.out.println(stus[i].toString()); } } }
标签:
原文地址:http://www.cnblogs.com/wenwangt/p/4946271.html