...
This code uses ==
to compare two Integer
objects. According to guideline EXP01-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.
...
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 the equals()
method instead of ==
to compare wrapper classes (See guideline EXP03-J for further details.).
Compliant Solution
Using object1.equals(object2) only compares the values of the objects. Now, the results will be true
, as expected.
...
Code Block | ||
---|---|---|
| ||
public class Wrapper { public static void main(String[] args) { // Create an array list of integers, where each element // is greater than 127 ArrayList<Integer> list1 = new ArrayList<Integer>(); for(int i = 0; i < 10; i++) { list1.add(i + 1000); } // Create another array list of integers, where each element // is the same as the first one ArrayList<Integer> list2 = new ArrayList<Integer>(); for(int i = 0; i < 10; i++) { list2.add(i + 1000); } int counter = 0; for(int i = 0; i < 10; i++) { if(list1.get(i).equals(list2.get(i))) { counter++; } } System.out.println(counter); } } |
Exceptions
EXP-03-EX1: Boolean
variables can be compared using relational operators, however, if instantiated as an object this is counterproductive.
...
Using the equal and not equal operators to compare boxed primitives can lead to erroneous comparisons.
Rule Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP03- J | low | likely | medium | P6 | L2 |
...