How to properly compare two Integers in Java?

前端 未结 10 1564
情歌与酒
情歌与酒 2020-11-21 07:06

I know that if you compare a boxed primitive Integer with a constant such as:

Integer a = 4;
if (a < 5)

a will automaticall

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 07:45

    Calling

    if (a == b)
    

    Will work most of the time, but it's not guaranteed to always work, so do not use it.

    The most proper way to compare two Integer classes for equality, assuming they are named 'a' and 'b' is to call:

    if(a != null && a.equals(b)) {
      System.out.println("They are equal");
    }
    

    You can also use this way which is slightly faster.

       if(a != null && b != null && (a.intValue() == b.intValue())) {
          System.out.println("They are equal");
        } 
    

    On my machine 99 billion operations took 47 seconds using the first method, and 46 seconds using the second method. You would need to be comparing billions of values to see any difference.

    Note that 'a' may be null since it's an Object. Comparing in this way will not cause a null pointer exception.

    For comparing greater and less than, use

    if (a != null && b!=null) {
        int compareValue = a.compareTo(b);
        if (compareValue > 0) {
            System.out.println("a is greater than b");
        } else if (compareValue < 0) {
            System.out.println("b is greater than a");
        } else {
                System.out.println("a and b are equal");
        }
    } else {
        System.out.println("a or b is null, cannot compare");
    }
    

提交回复
热议问题