很多时候我们写Compareto方法是用于排序,那么排序就涉及到数据位置交换。

所以要注意compareto返回值的含义,通过一个例子来看一下:

假设对象的num属性作为比较标准,对象为testVO

第一种写法:

public int compareTo(testVO o) {
  return this.num - o.getNum();    
}

如果返回值<=0,不进行交换。

如果返回值>0,进行交换,且o的num比this的num小,含义为小于当前对象则交换,升序排列。

第二种写法:

public int compareTo(testVO o) {
  return o.getNum() - this.num;    
}

如果返回值<=0,不进行交换。

如果返回值>0,进行交换,且o的num比this的num大,含义为大于当前对象则交换,降序排列。

相关文章:

  • 2021-07-25
  • 2021-06-28
  • 2021-06-10
  • 2021-11-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2017-11-23
  • 2021-04-27
  • 2022-12-23
  • 2021-11-23
  • 2021-10-15
  • 2021-07-12
  • 2022-12-23
相关资源
相似解决方案