整数值比较
我是一个新手Java编码器,我只是读取一个整数类的变量,可以在API中描述三种不同的方式。 我有以下代码:
if (count.compareTo(0)) { System.out.println(out_table); count++; }
这是在循环内部,只输出out_table
。
我的目标是弄清楚如何查看整数count > 0
的值。
我意识到count.compare(0)
是正确的方法吗? 还是count.equals(0)
?
我知道count == 0
是不正确的。 这是正确的吗? 是否存在值count=0
的值比较运算符?
整数是自动装箱的,所以你可以这样做
if (count > 0) { .... }
要确定Integer
是否大于0,您可以:
-
检查
compareTo(O)
返回正数:if (count.compareTo(0) > 0) ...
但那看起来很傻,不是吗? 更好……
-
使用自动装箱 1 :
if (count > 0) ....
这相当于:
if (count.intValue() > 0) ...
重要的是要注意“
==
”是这样计算的,其中Integer
操作数是未装箱的而不是装入的操作数。 否则,当count
初始化为new Integer(0)
时,count == 0
将返回false(因为“==
”测试引用相等)。
1从技术上讲,第一个示例使用自动装箱 (在Java 1.5之前,您无法将int
传递给compareTo
),第二个示例使用取消装箱 。 合并后的function通常简称为“自动装箱”,通常会将其扩展为调用两种类型的转换“自动装箱”。 对于我对术语的松散使用,我深表歉意。
最好避免不必要的自动装箱有两个原因。
首先,它比int < int
慢一点,因为你(有时)创建了一个额外的对象;
void doSomethingWith(Integer integerObject){ ... int i = 1000; doSomethingWith(i);//gets compiled into doSomethingWith(Integer.valueOf(i));
更大的问题是隐藏的自动装箱可以隐藏exception:
void doSomethingWith (Integer count){ if (count>0) // gets compiled into count.intValue()>0
使用null
调用此方法将抛出NullPointerException
。
java中的基元和包装器对象之间的分离总是被描述为速度的kludge。 Autoboxing几乎隐藏了这一点,但并不完全 - 只是为了跟踪类型而更加清晰。 因此,如果你有一个Integer对象,你可以调用compare()
或intValue()
,如果你有原语,只需直接检查值。
你也可以使用equals:
Integer a = 0; if (a.equals(0)) { // a == 0 }
这相当于:
if (a.intValue() == 0) { // a == 0 }
并且:
if (a == 0) { }
(Java编译器自动添加intValue ())
请注意,自动装箱/自动装箱可能会带来很大的开销(尤其是内部循环)。
虽然你当然可以在Integer实例上使用compareTo
方法,但在阅读代码时并不清楚,所以你应该避免这样做。
Java允许您使用自动装箱(请参阅http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html )直接与int进行比较,因此您可以执行以下操作:
if (count > 0) { }
并且Integer
实例count
会自动转换为int
以进行比较。
如果您无法理解这一点,请查看上面的链接,或者想象它是这样做的:
if (count.intValue() > 0) { }
还有一点要注意的是,如果第二个值是另一个Integer对象而不是文字’0’,’==’运算符会比较对象指针而不会自动取消装箱。
即:
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
好吧,我可能会迟到但我想分享一些事情:
给定输入:System.out.println(isGreaterThanZero(-1));
public static boolean isGreaterThanZero(Integer value) { return value == null?false:value.compareTo(0) > 0; }
返回false
public static boolean isGreaterThanZero(Integer value) { return value == null?false:value.intValue() > 0; }
返回true所以我认为在你的’compareTo’中会更准确。