如何比较两个整数? [英] How do I compare two Integers?
问题描述
我必须比较两个 Integer
对象(不是 int
)。
I have to compare two Integer
objects (not int
). What is the canonical way to compare them?
Integer x = ...
Integer y = ...
我可以想到这个:
if (x == y)
==
运算符只比较引用,因此这将只适用于较小的整数值。
The ==
operator only compares references, so this will only work for lower integer values. But perhaps auto-boxing kicks in...?
if (x.equals(y))
这看起来像一个昂贵的操作。
This looks like an expensive operation. Are there any hash codes calculated this way?
if (x.intValue() == y.intValue())
有点冗长...
strong> EDIT:感谢您的回复。虽然我知道现在做什么,事实是分布在所有现有的答案(甚至删除的:)),我不知道,哪一个接受。所以我会接受最好的答案,它指所有三种比较的可能性,或至少前两个。
Thank you for your responses. Although I know what to do now, the facts are distributed on all of the existing answers (even the deleted ones :)) and I don't really know, which one to accept. So I'll accept the best answer, which refers to all three comparison possibilities, or at least the first two.
推荐答案
是equals方法所做的:
This is what the equals method does:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
正如你所看到的,没有哈希码计算,其他操作发生在那里。虽然 x.intValue()== y.intValue()
可能会稍微快些,你进入微优化领域。加上编译器可能优化 equals()
调用,虽然我不知道这一定。
As you can see, there's no hash code calculation, but there are a few other operations taking place there. Although x.intValue() == y.intValue()
might be slightly faster, you're getting into micro-optimization territory there. Plus the compiler might optimize the equals()
call anyway, though I don't know that for certain.
我一般会使用原始 int
,但如果我不得不使用 Integer
,我会坚持使用 equals()
。
I generally would use the primitive int
, but if I had to use Integer
, I would stick with equals()
.
这篇关于如何比较两个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!