Java Integer Comparison

Integer comparisons in Java are complex because intthey Integerbehave differently. I get this part.

But, as the example program example shows , (Integer)400(line # 4) behaves differently than (Integer)5(line # 3). Why is this?

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.format("1. 5              == 5            : %b\n", 5 == 5);
        System.out.format("2. (int)5         == (int)5       : %b\n", (int)5 == (int)5);
        System.out.format("3. (Integer)5     == (Integer)5   : %b\n", (Integer)5 == (Integer)5);
        System.out.format("4. (Integer)400   == (Integer)400 : %b\n", (Integer)400 == (Integer)400);
        System.out.format("5. new Integer(5) == (Integer)5   : %b\n", new Integer(5) == (Integer)5);
    }
}

Result

1. 5              == 5            : true  // Expected
2. (int)5         == (int)5       : true  // Expected
3. (Integer)5     == (Integer)5   : true  // Expected
4. (Integer)400   == (Integer)400 : false // WHAT?
5. new Integer(5) == (Integer)5   : false // Odd, but expected
+4
source share
3 answers

From JLS

If the p value in the box is true, false, a byte or char in the range from \ u0000 to \ u007f or int, or a short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two p box transforms. It always happens that r1 == r2.

, p . . - . , . , . . ( ) .

, , , . , , char , int long -32K + 32K.

+2

Integer :

(Integer)400 --- Integer.valueOf(400)

valueOf is implemented such that certain numbers are "pooled", and it returns the same instance for values smaller than 128.

(Integer)5 128, (Integer)400 .

:

3. (Integer)5     == (Integer)5   : true  // Expected -- since 5 is pooled (i.e same reference)

4. Integer(400)   == (Integer)400 : false // WHAT? -- since 400 is not pooled (i.e different reference)
+6

JLS:

If the p value in the box is true, false, a byte or char in the range from \ u0000 to \ u007f or int, or a short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two p box transforms. It always happens that r1 == r2.

Shorter Integeruses the pool, so for numbers from -128 to 127 you will always get the same object after the box, and, for example, new Integer(120) == new Integer(120)will be evaluated to true, but new Integer(130) == new Integer(130)will be evaluated as false.

+4
source

All Articles