How to properly compare two Integers in Java?

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

    this method compares two Integer with null check, see tests

    public static boolean compare(Integer int1, Integer int2) {
        if(int1!=null) {
            return int1.equals(int2);
        } else {
            return int2==null;
        }
        //inline version:
        //return (int1!=null) ? int1.equals(int2) : int2==null;
    }
    
    //results:
    System.out.println(compare(1,1));           //true
    System.out.println(compare(0,1));           //false
    System.out.println(compare(1,0));           //false
    System.out.println(compare(null,0));        //false
    System.out.println(compare(0,null));        //false
    System.out.println(compare(null,null));     //true
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题