How to properly compare two Integers in Java?

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

    == checks for reference equality, however when writing code like:

    Integer a = 1;
    Integer b = 1;
    

    Java is smart enough to reuse the same immutable for a and b, so this is true: a == b. Curious, I wrote a small example to show where java stops optimizing in this way:

    public class BoxingLol {
        public static void main(String[] args) {
            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                Integer a = i;
                Integer b = i;
                if (a != b) {
                    System.out.println("Done: " + i);
                    System.exit(0);
                }
            }
            System.out.println("Done, all values equal");
        }
    }
    

    When I compile and run this (on my machine), I get:

    Done: 128
    

提交回复
热议问题