例如现在有一个自定义的类,
[java] view plain copy class Score{ public int score; public int time; public int getScore() { return score; } public void setScore(int score) { this.score = score; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } public Score(int score, int time) { super(); this.score = score; this.time = time; } } 如果对一个对象数组进行排序 [html] view plain copy Score[] score=new Score[n]; Arrays.sort(score); 这样是没法实现的,而对基本的数据类型可以这样排序是因为其都实现了Comparable<T>接口例如
[java] view plain copy public final class Integer extends Number implements <strong>Comparable<Integer></strong> { public final class String implements java.io.Serializable, <strong>Comparable<String></strong>, CharSequence { 所以这里的Score对象必须先实现自己的比较器才能用上述类似的方式进行排序
2,比较
(1).Comparator 和 Comparable都是Java中的内部比较器接口,都是用来实现对一个自定义的类进行排序
(2). 不同的是实现Comparable接口是定义在类的内部,比较代码需要嵌入类的内部结构中
Comparator 实现在类的外部,单独实现第一个比较器,不需要对原来的类进行结构上的变化,属于无侵入式的。
具体到上面的例子
Comparable<T>内部侵入式实现比较器
[java] view plain copy class Score implements Comparable<Score>{ public int score; public int time; public int getScore() { return score; } public void setScore(int score) { this.score = score; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } @Override public int compareTo(Score o) { if(this.time>o.time) return 1; else if(this.time==o.time) return 0; else return -1; } public Score(int score, int time) { super(); this.score = score; this.time = time; } } 然后在主类中直接比较 Arrays.sort(score);
Comparator <T>无侵入式实现比较器,只需要单独写一个比较器实现类ScoreComparator,或者写成匿名类形式
[java] view plain copy /* 单独写成一个类 */ class ScoreComparator implements Comparator<Score>{ @Override public int compare(Score o1, Score o2) { if(o1.time>o2.time) return 1; else if(o1.time==o2.time) return 0; else return -1; } }然后在主类中带入比较器类Arrays.sort(score, new ScoreComparator());
也可以写成匿名类:
Arrays.sort(score, new Comparator<TestComparator>() { @Override public int compare(TestComparator o1, TestComparator o2) { //按逆序排序 if (o1.time < o2.time) return 1; else if (o1.time > o2.time) return -1; else { return 0; } } });