怎么根据Comparable方法中的compareTo方法的返回值的正负 判断升序 还是 降序?

public int compareTo(Student o) {

        return this.age - o.age; // 比较年龄(年龄的升序)
    }

 

应该理解成return (-1)×(this.age-o.age)计算机没有所谓的正序和逆序,他只管大还是小,你给他小的放前面,大的放后面,然后乘负一,整个顺序就反过来了

 

比如:this.age=23, o.age=24,那么:

this.age - o.age=-1 这样系统就认为this比o小,所以排在this排在前面,就是升序了;

如果写成  o.age - this.age 就相当于 -(this.age - o.age)=1,这样系统就认为this比o大了,所以this排在后面,就是降序了。

 

更明白的理解就是:

return this.age > o.age ? -1 : 1;   降序排列   等价于 return o.age - this.age

return this.age > o.age ? 1 : -1;   升序排列   等价于  return this.age - o.age

posted @ 2020-11-17 16:53  風封  阅读(335)  评论(0编辑  收藏  举报