简体   繁体   English

如何重写compareTo()。 如果它是可能的

[英]how to override compareTo(). If it's possible

public int compareTo(Object obj){
   Books bk = (Books) bk;
   return this.id - obj.id;
}

my code works fine when id is an Integer and when is a positive value. idInteger且为正值时,我的代码工作正常。 Is it possible for id to be a negative value? id是否可能为负值? How to change the code for that? 如何更改代码?

The following is perhaps the easiest way to implement it: 以下可能是实现它的最简单方法:

public int compareTo(Object obj) {
   Books bk = (Books)obj;
   return Integer.compare(this.id, bk.id);
}

Your current version is almost correct, except that it is susceptible to integer overflow. 您的当前版本几乎是正确的,除了它容易受到整数溢出的影响。

When you override compareTo you get to define the answer to these questions. 当您覆盖compareTo您将定义这些问题的答案。 It completely depends on your program whether it's possible for id to be a negative value. id是否可能为负值完全取决于您的程序。 The question you have to ask yourself is "what does it mean for one book to be 'larger' (or smaller) than another one?". 您必须问自己的问题是“一本书比另一本书“更大”(或更小)意味着什么? If the answer is just which ever has the larger id is a larger Book, then your implementation is fine, except for one minor mistake: 如果答案是id越大的书越大,那么您的实现就可以了,除了一个小错误:

public int compareTo(Object obj){
   Books bk = (Books) obj;
   return this.id - bk.id;
}

You must be able to return a negative value. 必须能够返回负值。 From the Comparable specification, if 根据Comparable规范,如果

a.compareTo(b) > 0

then 然后

b.compareTo(a) < 0

Otherwise you could not use compareTo() to stablish an order 否则,您将无法使用compareTo() 订单

I made it work :D 我成功了:D

return (this.id > bk.id ) ? -1: (this.id < bk.id) ? 1:0 ;

this works how I wanted it but thanks for your reply 这是我想要的,但是谢谢你的回复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM