Java中Comparator接口的方法compare()为什么不能返回一个差值呢?

lin505494784 2014-08-13 03:11:53
问题如题,具体情况直接贴代码了。
Student类:

package com.lin;
public class Student {
private int age;
private int number;

public Student(int age, int number) {
this.age = age;
this.number = number;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}

}

ComparatorTest类:

package com.lin;

import java.util.Comparator;

public class ComparatorTest implements Comparator<Student> {

@Override
public int compare(Student o1, Student o2) {
if(o1.getAge() < o2.getAge()){
int num = o1.getAge() - o2.getAge();
// System.out.println(num);
return num;
}else{
int num = o2.getAge() - o1.getAge();
// System.out.println(num);
return num;
}
}
}


测试类:

package com.lin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
Student s1 = new Student(12,789456);
Student s2 = new Student(13,789455);
Student s3 = new Student(14,789454);
Student s4 = new Student(15,789453);
Student s5 = new Student(16,789452);
list.add(s2);
list.add(s5);
list.add(s3);
list.add(s1);
list.add(s4);
Collections.sort(list, new ComparatorTest());
for(Student s:list){
System.out.println(s.getAge());
}
}
}

运行结果:

13
16
14
12
15

为什么不能排序呢?
...全文
334 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
lin505494784 2014-08-14
  • 打赏
  • 举报
回复
了解了,我多此一举了……
S117 2014-08-13
  • 打赏
  • 举报
回复
你写错了吧 return o1.getAge() - o2.getAge(); 就可以了
拯救司马 2014-08-13
  • 打赏
  • 举报
回复
跟sort方法有关, 源码中通过比较compare返回的值(>0,=0,<0)确定的是否要调换数组元素的位置来完成排序。 感兴趣的话可以去看看源代码
vnvlyp 2014-08-13
  • 打赏
  • 举报
回复
你这样写compare那不永远返回的是非正值。。意思就是说照你这么比,o1永远比o2要小那当然不能排序。。
public int compare(Student o1, Student o2) {
    if(o1.getAge() < o2.getAge()){
        int num = o1.getAge() - o2.getAge();
        return num;
    }else{
        int num = o2.getAge() - o1.getAge();
        return num;
    }
}
按age升序排列直接这样啊。。
public int compare(Student o1, Student o2) {
    return o1.getAge() - o2.getAge();
}

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧