我是一名 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
?
要弄清楚是否Integer
大于0,则可以:
-
检查是否compareTo(O)
返回正数:
if (count.compareTo(0) > 0)
...
但这看起来很愚蠢,不是吗?最好只是...
-
use autoboxing http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html1:
if (count > 0)
....
这相当于:
if (count.intValue() > 0)
...
重要的是要注意“==
" 是这样评估的,Integer
操作数未装箱而不是int
操作数装箱。否则,count == 0
时会返回 falsecount
被初始化为new Integer(0)
(因为 ”==
“测试参考相等性)。
1Technically, the first example uses autoboxing http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7 (before Java 1.5 you couldn't pass an int
to compareTo
) and the second example uses unboxing http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.8. 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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)