compareTo返回值为-1 、 1 、 0 的排序问题

首先,先看代码内容:(希望大家自己可以运行尝试,以加深记忆和理解)

 

package s11;

 

import java.util.Comparator;

import java.util.TreeSet;

 

class Student implements Comparable {

String name;

int age;

int classNum;

 

public Student() {

}

 

public Student(String name, int age, int classNum) {

this.name = name;

this.age = age;

this.classNum = classNum;

}

 

public String toString() {

return "Student [name=" + name + ", age=" + age + ", classNum="

+ classNum + "]";

}

 

public int compareTo(Object o) {

Student s = (Student) o;

return this.classNum - s.classNum;

}

}

 

public class Studentdemo {

public static void main(String[] args) {

TreeSet ts1 = new TreeSet(

new Comparator() {

public int compare(Object o1,Object o2) {

Student s1 = (Student)o1;

Student s2 = (Student)o2;

return s1.age > s2.age ? 1 : -1;

}

});

ts1.add(new Student("mm",21,97005));

ts1.add(new Student("jerry",19,97003));

ts1.add(new Student("tom",16,97004));

ts1.add(new Student("mm",28,97008));

ts1.add(new Student("mm",23,97006));

System.out.println("语句return s1.age > s2.age ? 1 : -1;是按照???排列的:");

System.out.println(ts1);

}

}

这是运行结果:

 

语句return s1.age > s2.age ? 1 : -1;是按照升序(由小到大)排列的:

[Student [name=tom, age=16, classNum=97004], 

Student [name=jerry, age=19, classNum=97003], 

Student [name=mm, age=21, classNum=97005], 

Student [name=mm, age=23, classNum=97006],

Student [name=mm, age=28, classNum=97008]]

也就是说当语句return s1.age > s2.age ? 1 : -1;的返回值为1时,也就是说 s1的值大于s2的值时 ,compareTo是按照升序(由小到大)排序的!

当返回值为-1时,也就是说 s1的值小于s2的值时 ,compareTo是按照降序(由大到小)排序的!

当返回值为0时,s1等于s2的值,如果数值全部相等则排序也同样按照初始顺序排列,如果只有前两个数值相等,那么,compareTo会继续比较下一组s1 与 s2的值,同样, s1的值大于s2的值时 ,compareTo是按照升序(由小到大)排序的, s1的值小于s2的值时 ,compareTo是按照降序(由大到小)排序的!希望大家今天能彻底明白,不枉辛苦一字,谢谢!

你可能感兴趣的:(java)