java中的类实现comparable接口 用于排序
import java.util.Arrays;
public class SortApp {
public static void main(String[] args) {
Student[] stus = new Student[3];
stus[0] = new Student(11, 99);
stus[1] = new Student(13, 92);
stus[2] = new Student(13, 89);
Arrays.sort(stus);
for (Student student : stus) {
System.out.println("age=" + student.getAge() + ";" + "score="
+ student.getScore());
}
}
static class Student implements Comparable<Student> {
private int age;
private int score;
public Student() {
}
public Student(int age, int score) {
this.age = age;
this.score = score;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int compareTo(Student o) {
int result = this.age - o.age;// o 表示待要比较的对象 result为正 将升序排列 为负将降序排序
if (result != 0) {
return result;
} else {
return this.score - o.score;//如果result=0 将比较第二列
}
}
}
}
上面的例子我们在hadoop中主要是将一行作为一个key进行排序,因为hadoop默认的排序只针对key,value不排序,如要对value排序,我们需要自定义排序规则,将keyvalue同时作为key进行
posted on 2015-09-10 15:05 ggbond1988 阅读(262) 评论(0) 编辑 收藏 举报