Java 整数值比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/953180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Integer value comparison
提问by phill
I'm a newbie Java coder and I just read a variable of an integer class can be described three different ways in the API. I have the following code:
我是一个新手 Java 编码员,我刚刚阅读了一个整数类的变量,可以在 API 中以三种不同的方式进行描述。我有以下代码:
if (count.compareTo(0)) {
System.out.println(out_table);
count++;
}
This is inside a loop and just outputs out_table
.
My goal is to figure out how to see if the value in integer count > 0
.
这是在一个循环内,只是输出out_table
。
我的目标是弄清楚如何查看 integer 中的值count > 0
。
I realize the count.compare(0)
is the correct way? or is it count.equals(0)
?
我意识到这count.compare(0)
是正确的方法吗?或者是count.equals(0)
吗?
I know the count == 0
is incorrect. Is this right? Is there a value comparison operator where its just count=0
?
我知道这count == 0
是不正确的。这是正确的吗?是否有一个值比较运算符count=0
?
采纳答案by Nathaniel Flath
Integers are autounboxed, so you can just do
整数是自动拆箱的,所以你可以这样做
if (count > 0) {
....
}
回答by Michael Myers
To figure out if an Integer
is greater than 0, you can:
要确定 anInteger
是否大于 0,您可以:
check if
compareTo(O)
returns a positive number:if (count.compareTo(0) > 0) ...
But that looks pretty silly, doesn't it? Better just...
use autoboxing1:
if (count > 0) ....
This is equivalent to:
if (count.intValue() > 0) ...
It is important to note that "
==
" is evaluated like this, with theInteger
operand unboxed rather than theint
operand boxed. Otherwise,count == 0
would return false whencount
was initialized asnew Integer(0)
(because "==
" tests for reference equality).
检查是否
compareTo(O)
返回正数:if (count.compareTo(0) > 0) ...
但这看起来很傻,不是吗?最好只是...
使用自动装箱1:
if (count > 0) ....
这相当于:
if (count.intValue() > 0) ...
重要的是要注意“
==
”是这样计算的,Integer
操作数未装箱而不是int
操作数装箱。否则,count == 0
将在count
初始化为时返回 falsenew Integer(0)
(因为 "==
" 测试引用相等性)。
1Technically, the first example uses autoboxing(before Java 1.5 you couldn't pass an int
to compareTo
) and the second example uses unboxing. The combined feature is often simply called "autoboxing" for short, which is often then extended into calling both types of conversions "autoboxing". I apologize for my lax usage of terminology.
1从技术上讲,第一个示例使用自动装箱(在 Java 1.5 之前,您不能传递int
to compareTo
),第二个示例使用取消装箱。组合功能通常简称为“自动装箱”,然后通常扩展为将两种类型的转换称为“自动装箱”。我为我对术语的使用松懈而道歉。
回答by jpdaigle
Although you could certainly use the compareTo
method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.
虽然您当然可以在compareTo
Integer 实例上使用该方法,但在阅读代码时并不清楚,因此您应该避免这样做。
Java allows you to use autoboxing (see http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) to compare directly with an int, so you can do:
Java 允许您使用自动装箱(请参阅http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html)直接与 int 进行比较,因此您可以执行以下操作:
if (count > 0) { }
And the Integer
instance count
gets automatically converted to an int
for the comparison.
并且Integer
实例count
会自动转换为 anint
进行比较。
If you're having trouble understanding this, check out the link above, or imagine it's doing this:
如果您无法理解这一点,请查看上面的链接,或者想象它正在这样做:
if (count.intValue() > 0) { }
回答by Steve B.
It's better to avoid unnecessary autoboxing for 2 reasons.
出于两个原因,最好避免不必要的自动装箱。
For one thing, it's a bit slower than int < int
, as you're (sometimes) creating an extra object;
一方面,它比 慢一点int < int
,因为您(有时)正在创建一个额外的对象;
void doSomethingWith(Integer integerObject){ ...
int i = 1000;
doSomethingWith(i);//gets compiled into doSomethingWith(Integer.valueOf(i));
The bigger issue is that hidden autoboxing can hide exceptions:
更大的问题是隐藏的自动装箱可以隐藏异常:
void doSomethingWith (Integer count){
if (count>0) // gets compiled into count.intValue()>0
Calling this method with null
will throw a NullPointerException
.
使用 with 调用此方法null
将抛出一个NullPointerException
.
The split between primitives and wrapper objects in java was always described as a kludge for speed. Autoboxing almost hides this, but not quite - it's cleaner just to keep track of the type. So if you've got an Integer object, you can just call compare()
or intValue()
, and if you've got the primitive just check the value directly.
Java 中基元和包装器对象之间的分裂总是被描述为对速度的一种混杂。自动装箱几乎隐藏了这一点,但并非完全隐藏 - 仅跟踪类型就更干净了。因此,如果您有一个 Integer 对象,您只需调用compare()
or intValue()
,如果您有原语,只需直接检查该值。
回答by dfa
You can also use equals:
您还可以使用等于:
Integer a = 0;
if (a.equals(0)) {
// a == 0
}
which is equivalent to:
这相当于:
if (a.intValue() == 0) {
// a == 0
}
and also:
并且:
if (a == 0) {
}
(the Java compiler automatically adds intValue())
(Java编译器自动添加intValue())
Note that autoboxing/autounboxing can introduce a significant overhead (especially inside loops).
请注意,自动装箱/自动拆箱会引入大量开销(尤其是内部循环)。
回答by Sogger
One more thing to watch out for is if the second value was another Integer object instead of a literal '0', the '==' operator compares the object pointers and will not auto-unbox.
需要注意的另一件事是,如果第二个值是另一个 Integer 对象而不是文字“0”,“==”运算符会比较对象指针并且不会自动拆箱。
ie:
IE:
Integer a = new Integer(0);
Integer b = new Integer(0);
int c = 0;
boolean isSame_EqOperator = (a==b); //false!
boolean isSame_EqMethod = (a.equals(b)); //true
boolean isSame_EqAutoUnbox = ((a==c) && (a.equals(c)); //also true, because of auto-unbox
//Note: for initializing a and b, the Integer constructor
// is called explicitly to avoid integer object caching
// for the purpose of the example.
// Calling it explicitly ensures each integer is created
// as a separate object as intended.
// Edited in response to comment by @nolith
回答by lawrence wamala
well i might be late on this but i would like to share something:
好吧,我可能会迟到,但我想分享一些东西:
Given the input: System.out.println(isGreaterThanZero(-1));
给定输入: System.out.println(isGreaterThanZero(-1));
public static boolean isGreaterThanZero(Integer value) {
return value == null?false:value.compareTo(0) > 0;
}
Returns false
返回假
public static boolean isGreaterThanZero(Integer value) {
return value == null?false:value.intValue() > 0;
}
Returns true So i think in yourcase 'compareTo' will be more accurate.
返回 true 所以我认为在你的情况下 'compareTo' 会更准确。