整数值比较

发布于 2024-07-23 02:56:46 字数 481 浏览 7 评论 0原文

我是一名 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

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:

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.

I realize the count.compare(0) is the correct way? or is it count.equals(0)?

I know the count == 0 is incorrect. Is this right? Is there a value comparison operator where its just count=0?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

夜雨飘雪 2024-07-30 02:56:46

要确定 Integer 是否大于 0,您可以:

  • 检查 compareTo(O) 是否返回正数:

    if (count.compareTo(0) > 0) 
           ... 
      

    但这看起来很愚蠢,不是吗? 最好...

  • 使用自动装箱1

    if(计数> 0) 
          .... 
      

    这相当于:

    if (count.intValue() > 0) 
          ... 
      

    需要注意的是,“==”的计算方式如下,Integer 操作数未装箱,而不是 int 操作数已装箱。 否则,当 count 初始化为 new Integer(0) 时,count == 0 将返回 false(因为“==" 测试引用相等性)。

1从技术上讲,第一个示例使用 自动装箱(在 Java 1.5 之前,您无法将 int 传递给 compareTo),第二个示例使用 拆箱。 组合功能通常简称为“自动装箱”,然后通常扩展为将两种类型的转换称为“自动装箱”。 我为我对术语的不严谨使用表示歉意。

To figure out if an Integer is greater than 0, you can:

  • 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 the Integer operand unboxed rather than the int operand boxed. Otherwise, count == 0 would return false when count was initialized as new Integer(0) (because "==" tests for reference equality).

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.

戏舞 2024-07-30 02:56:46

整数是自动拆箱的,所以你可以这样做

if (count > 0) {
    .... 
}

Integers are autounboxed, so you can just do

if (count > 0) {
    .... 
}
脱离于你 2024-07-30 02:56:46

最好避免不必要的自动装箱,原因有两个。

一方面,它比 int < 慢一点。 int,因为您(有时)创建一个额外的对象;

void doSomethingWith(Integer integerObject){ ...
  int i = 1000;
  doSomethingWith(i);//gets compiled into doSomethingWith(Integer.valueOf(i));

更大的问题是隐藏的自动装箱可以隐藏异常:

void doSomethingWith (Integer count){
  if (count>0)  // gets compiled into count.intValue()>0

使用 null 调用此方法将抛出 NullPointerException

Java 中基元和包装对象之间的划分总是被描述为速度的混杂。 自动装箱几乎隐藏了这一点,但不完全是这样——仅仅跟踪类型就更干净了。 因此,如果您有一个 Integer 对象,则只需调用 compare()intValue() 即可,如果您有原语,则只需直接检查值即可。

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;

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.

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.

挽你眉间 2024-07-30 02:56:46

您还可以使用 equals: ,

 Integer a = 0;

 if (a.equals(0)) {
     // a == 0
 }

它相当于:

 if (a.intValue() == 0) {
     // a == 0
 }

以及:

 if (a == 0) {

 }

(Java 编译器自动添加 intValue())

请注意,自动装箱/自动拆箱可能会带来很大的开销(尤其是在循环内部)。

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())

Note that autoboxing/autounboxing can introduce a significant overhead (especially inside loops).

酒绊 2024-07-30 02:56:46

尽管您当然可以在 Integer 实例上使用 compareTo 方法,但在阅读代码时并不清楚,因此您应该避免这样做。

Java 允许您使用自动装箱(请参阅 http:// java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) 直接与 int 进行比较,因此您可以执行以下

if (count > 0) { }

操作: Integer 实例 < code>count 自动转换为 int 进行比较。

如果您无法理解这一点,请查看上面的链接,或者想象它正在这样做:

if (count.intValue() > 0) { }

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.

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:

if (count > 0) { }

And the Integer instance count gets automatically converted to an int for the comparison.

If you're having trouble understanding this, check out the link above, or imagine it's doing this:

if (count.intValue() > 0) { }
彩扇题诗 2024-07-30 02:56:46

还要注意的另一件事是,如果第二个值是另一个 Integer 对象而不是文字“0”,则“==”运算符会比较对象指针,并且不会自动拆箱。

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

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.

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
猛虎独行 2024-07-30 02:56:46

好吧,我可能会迟到,但我想分享一些东西:

鉴于输入:
System.out.println(isGreaterThanZero(-1));

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.compareTo(0) > 0;
}

返回

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.intValue() > 0;
}

返回真
所以我认为在你的情况下“compareTo”会更准确。

well i might be late on this but i would like to share something:

Given the input:
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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文