Here is en example where iterating over an array is much faster than iterating over a list directly. This we can apply if we have to iterate a list over multiple time in a single thread.
private static void checkArrayList() {
ArrayList listOne = new ArrayList();
long startTime = System.nanoTime();
for (int i = 0; i <span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>< 1000; i++) {
listOne.add(i);
}
// Total time taken to construct an array list with 1000 elements
System.out.println("Total Time 1:" + (System.nanoTime() - startTime));
// Iterate entire list
startTime = System.nanoTime();
for (int k : listOne) {
}
// total time to iterate over 1000 elements
System.out.println("Total Time 2:" + (System.nanoTime() - startTime));
Integer a[] = new Integer[1000];
// Convert list into array
startTime = System.nanoTime();
listOne.toArray(a);
// time to convert list into array
System.out.println("Total Time 3:" + (System.nanoTime() - startTime));
// Iterate entire array
startTime = System.nanoTime();
for (int k : a) {
}
// total time taken to iterate over array
System.out.println("Total Time 4:" + (System.nanoTime() - startTime));
}