How to properly compare two Integers in Java?

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

    == will still test object equality. It is easy to be fooled, however:

    Integer a = 10;
    Integer b = 10;
    
    System.out.println(a == b); //prints true
    
    Integer c = new Integer(10);
    Integer d = new Integer(10);
    
    System.out.println(c == d); //prints false
    

    Your examples with inequalities will work since they are not defined on Objects. However, with the == comparison, object equality will still be checked. In this case, when you initialize the objects from a boxed primitive, the same object is used (for both a and b). This is an okay optimization since the primitive box classes are immutable.

提交回复
热议问题