Integer value comparison

后端 未结 7 1287
北恋
北恋 2021-02-02 09:31

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.         


        
7条回答
  •  后悔当初
    2021-02-02 10:16

    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.

提交回复
热议问题