实现比较方法的规则 [英] Rules to implement compare method
本文介绍了实现比较方法的规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谢谢
解决方案
来自比较器API :
- 实现者必须确保所有x和y的sgn(compare(x,y))== -sgn(compare(y,x))。 (这意味着当且仅当compare(y,x)抛出
异常时,compare(x,y)必须抛出异常。)
- 实现者还必须确保该关系是传递的:((compare(x,y)> 0)&&(compare(y,z)> 0))暗示比较(x,z)> 0.
- 最后,实现者必须确保compare(x,y)== 0表示所有z的sgn(compare(x,z))== sgn(compare(y,z))。
- 通常情况如此,但并非严格要求(compare(x,y)== 0)==(x.equals(y))。一般来说,违反此条件的任何
比较器都应清楚地表明这个
的事实。建议的语言是注意:这个比较器强加
与equals不一致的订单。
like compareTo, that have to be "reflexive, antisymmetric and transitive", are there any rules to implement the compare method?? thanks
解决方案
From Comparator API:
- The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)
- The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
- Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.
- It is generally the case, but not strictly required that (compare(x, y)==0) == (x.equals(y)). Generally speaking, any comparator that violates this condition should clearly indicate this fact. The recommended language is "Note: this comparator imposes orderings that are inconsistent with equals."
这篇关于实现比较方法的规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文