当前位置: 代码迷 >> J2SE >> Java中Comparator接口的步骤compare()为什么不能返回一个差值呢
  详细解决方案

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

热度:124   发布时间:2016-04-23 20:23:49.0
Java中Comparator接口的方法compare()为什么不能返回一个差值呢?
问题如题,具体情况直接贴代码了。
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

为什么不能排序呢?
------解决方案--------------------
你这样写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();
}

------解决方案--------------------
你写错了吧
return o1.getAge() - o2.getAge();
就可以了
  相关解决方案