java类经常面临排序问题,据我所知:java提供comparable和comparator两种比较方式:
1. comparable方法需要排序的类继承comparable接口,重写compareTo函数,但是只能实现一种对比方法(重写compareTo一次),例如:
类定义如下:
class Student implements Comparable{privateString name;privateString key;private floatscore;private intage;public Student(String key, String name, float score, intage) {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 intcompareTo(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 ListgetStudents(){
List col = new ArrayList();
Random rand= newRandom();
String valkey;intvalAge, 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(newStudent(valkey,valName, valAge, valScore));
}returncol;
}
通过Collections.sort(List)方法进行排序:
List grade =Student.getStudents();
Iterator 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{public intcompare(Student st1, Student st2){returnst1.getName().compareTo(st2.getName());
}
}
接下来我们通过排序进行测验,我们必须使用Collections.sort(List, Comparator)这个方法而不是Collections.sort(List)方法:
public classClassSort {public static voidmain(String []args) {//Student stu1 = new Student("wen", 90, 17);//Student stu2 = new Student("mike", 90, 18);//System.out.print("res:" + stu1.compareTo(stu2));
List grade =Student.getStudents();
Iterator iter =grade.iterator();//Collections.sort(grade);
Collections.sort(grade,newStudSortByName());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 voidprint(Student [] stus){for (int i = 0; i < stus.length; i++) {
System.out.println(stus[i].toString());
}
}
}
附注可执行代码如下:
packagecomparable;import java.util.*;importorg.apache.commons.lang3.RandomStringUtils;importorg.apache.commons.lang3.builder.Diff;/*** Created by carl on 11/7/15.*/
class Student implements Comparable{privateString name;privateString key;private floatscore;private intage;public Student(String key, String name, float score, intage) {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 intcompareTo(Student ano){return (int)(this.score -ano.score);
}public static ListgetStudents(){
List col = new ArrayList();
Random rand= newRandom();
String valkey;intvalAge, 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(newStudent(valkey,valName, valAge, valScore));
}returncol;
}publicString getName(){returnname;
}public floatgetScore() {returnscore;
}public intgetAge() {returnage;
}
@OverridepublicString toString() {return "Student{" +
"name='" + name + '\'' +
", key='" + key + '\'' +
", score=" + score +
", age=" + age +
'}';
}
}//Student
class StudSortByName implements Comparator{public intcompare(Student st1, Student st2){returnst1.getName().compareTo(st2.getName());
}
}public classClassSort {public static voidmain(String []args) {//Student stu1 = new Student("wen", 90, 17);//Student stu2 = new Student("mike", 90, 18);//System.out.print("res:" + stu1.compareTo(stu2));
List grade =Student.getStudents();
Iterator iter =grade.iterator();//Collections.sort(grade);
Collections.sort(grade,newStudSortByName());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 voidprint(Student [] stus){for (int i = 0; i < stus.length; i++) {
System.out.println(stus[i].toString());
}
}
}