Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Noncompliant Code Example

This code uses == to compare two integer objects. According to EXP03-J. Do not compare String objects using equality or relational operators, for == to return true for two object references, they must point to the same underlying object. Results of using the == operator in this case will be misleading.

Code Block
bgColor#FFCCCC

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);
 
 }
}

These comparisons generate the output sequence: true, false, false and true. The cache in the Integer class can only make the integers from -127 to 128 refer to the same object, which explains the output of the above code. To avoid making such mistakes, use equals instead of == to compare wrapper classes (See EXP03-J for further details).

Compliant Solution

Using object1.equals(object2) only compares their values. Now, the results will be true, as expected.

Code Block
bgColor#CCCCFF

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));

 }
}

Noncompliant Code Example

Sometimes a list of integers is desired. Recall that the type parameter inside the angle brackets of a list cannot be of a primitive type. It is not possible to form an ArrayList<int>. With the help of the wrapper classs and autoboxing, storing primitive integer values in ArrayList<Integer> becomes possible.

...

If it were possible to expand the cache inside Integer (cache all the integer values -32K-32K, which means that all the int values may be autoboxed to the same Integer object), then the results may have differed.

Compliant Solution

This compliant solution uses the equals() method for performing comparisons of wrapped objects. It produces the correct output 10.

...