...
Code Block |
---|
import java.util.ArrayList; public class TestWrapper1 {  public static void main(String[] args) {   //create an array list of integers, which each element   //is more 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, which each element   //is the same with 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) == list2.get(i)) counter++;     //output the total equal number     System.out.println(counter);  } } |
In JDK 5.0, the output of this code is 0. But if we In this code, we want to count the same numbers of array list1 and array list2. Undoubtedly, the result are not the same as our expectation. But if we can set more caches inside Integer, then the result may be different!
Compliant solution
Code Block |
---|
public class TestWrapper1 {
 public static void main(String[] args) {
  //create an array list of integers, which each element
  //is more 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, which each element
  //is the same with 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++;
    //output the total equal number
    System.out.println(counter);
 }
}
|
Risk Assessment
The result is an undefined behavior, so it will exert a potential security risk.
...