How to properly compare two Integers in Java?

前端 未结 10 1340
情歌与酒
情歌与酒 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:27

    In my case I had to compare two Integers for equality where both of them could be null. Searched similar topic, didn't found anything elegant for this. Came up with a simple utility functions.

    public static boolean integersEqual(Integer i1, Integer i2) {
        if (i1 == null && i2 == null) {
            return true;
        }
        if (i1 == null && i2 != null) {
            return false;
        }
        if (i1 != null && i2 == null) {
            return false;
        }
        return i1.intValue() == i2.intValue();
    }
    
    //considering null is less than not-null
    public static int integersCompare(Integer i1, Integer i2) {
        if (i1 == null && i2 == null) {
            return 0;
        }
        if (i1 == null && i2 != null) {
            return -1;
        }
        return i1.compareTo(i2);
    }
    

提交回复
热议问题