Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider Java v3.0

...

Code Block
bgColor#FFCCCC
static Comparator<Integer>Comparator&lt;Integer&gt; cmp = new Comparator<Integer>Comparator&lt;Integer&gt;() {
  public int compare(Integer i, Integer j) {
    return i <&lt; j ? -1 : (i == j ? 0 : 1);
  } 
};

...

Code Block
bgColor#ccccff
public int compare(Integer i, Integer j) {
  return i <&lt; j ? -1 : (i >&gt; j ? 1 : 0) ;
}

Noncompliant Code Example

...

Code Block
bgColor#FFCCCC
public class Wrapper {
 public static void main(String[] args) {
   // Create an array list of integers, where each element 
   // is greater than 127
   ArrayList<Integer>ArrayList&lt;Integer&gt; list1 = new ArrayList<Integer>ArrayList&lt;Integer&gt;();
  
   for(int i = 0; i <&lt; 10; i++) {
     list1.add(i + 1000);
   }

   // Create another array list of integers, where each element
   // is the same as the first list
   ArrayList<Integer>ArrayList&lt;Integer&gt; list2 = new ArrayList<Integer>ArrayList&lt;Integer&gt;();
   
   for(int i = 0; i <&lt; 10; i++) {
     list2.add(i + 1000);
   }
 
   int counter = 0;
   for(int i = 0; i <&lt; 10; i++) {
     if(list1.get(i) == list2.get(i)) { 
       counter++;
     }
   }

   // print the counter
   System.out.println(counter);
 }
}

...

Code Block
bgColor#CCCCFF
public class Wrapper {
 public static void main(String[] args) {
   // Create an array list of integers, where each element
   // is greater than 127
   ArrayList<Integer>ArrayList&lt;Integer&gt; list1 = new ArrayList<Integer>ArrayList&lt;Integer&gt;();

   for(int i = 0; i <&lt; 10; i++) {
     list1.add(i + 1000);
   }

   // Create another array list of integers, where each element
   // is the same as the first one
   ArrayList<Integer>ArrayList&lt;Integer&gt; list2 = new ArrayList<Integer>ArrayList&lt;Integer&gt;();
   for(int i = 0; i <&lt; 10; i++) {
     list2.add(i + 1000);
   }
 
   int counter = 0;
   for(int i = 0; i <&lt; 10; i++) {
     if(list1.get(i).equals(list2.get(i))) { 
       counter++;
     }
   }
 
   System.out.println(counter);
 }
}

...

Code Block
bgColor#FFCCCC
Boolean b1 = new Boolean("true"&quot;true&quot;);
Boolean b2 = new Boolean("true"&quot;true&quot;);
if(b1 == b2) { // never equal
  // ...
}

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[Bloch 09|AA. Java References#Bloch 09]\] 4. "&quot;Searching for the One"&quot;
\[[Pugh 09|AA. Java References#Pugh 09]\] Using == to compare objects rather than .equals

...

EXP31-J. Avoid side effects in assertions      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;04. Expressions (EXP)      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;05. Scope (SCP)