...
Code Block |
---|
public class TestWrapper2 { Â public static void main(String[] args) { Â Â Â Â Integer i1 = 100; Â Â Â Â Integer i2 = 100; Â Â Â Â Integer i3 = 1000; Â Â Â Â Integer i4 = 1000; Â Â Â Â System.out.println(i1==i2); Â Â Â Â System.out.println(i1!=i2); Â Â Â Â System.out.println(i3==i4); Â Â Â Â System.out.println(i3!=i4); Â Â Â Â Â } } |
This code uses "==" to compare 2 Integer object, from EXP03-J we can know that for "==" to return true
for two object references, they must point to the same underlying object. So we can simply draw the conclusion that the results of using "==" operator in this code will be false. However,
Output of this code
Code Block |
---|
true false false true |
...
Here the cache in the Integer class can make the number from -127 to 128 refer to the same object, which clearly explains the result of above code. In case of thatmaking such mistakes, when we need to do some comparisons of these wrapper class, we should use equal instead "==" (see EXP03-J for details):
...
Code Block |
---|
public class TestWrapper2 { Â public static void main(String[] args) { Â Â Â Â Integer i1 = 100; Â Â Â Â Integer i2 = 100; Â Â Â Â Integer i3 = 1000; Â Â Â Â Integer i4 = 1000; Â Â Â Â System.out.println(i1.equals(i2)); Â Â Â Â System.out.println(i3.equals(i4));Â Â Â Â Â } }Â |
Now, the results are all trues, as we expected.
Noncompliant Code Example
...