I always use for each cycle when viewing the elements of a particular collection .
To check how much time each process of the loop takes, I encoded this way
public class LoopingDemo {
static ArrayList<String> arrayList = new ArrayList<String>();
static double start;
static double end;
public static void iterator() {
simpleForLoop();
System.out.println();
forEachLoop();
System.out.println();
useWhileLoop(arrayList);
System.out.println();
useForLoop(arrayList);
System.out.println();
enumerator();
}
public static void simpleForLoop(){
start = System.nanoTime();
for(int i=0;i<arrayList.size();i++){
String str = arrayList.get(i);
System.out.println(": "+str);
}
end = System.nanoTime();
System.out.println("Taken taken in simpleForLoop process: "
+ (end - start));
}
public static void forEachLoop() {
start = System.nanoTime();
for (String str : arrayList) {
System.out.println(str);
}
end = System.nanoTime();
System.out.println("Taken taken in forEachLoop process: "
+ (end - start));
}
public static void enumerator() {
start = System.nanoTime();
Enumeration<String> en = Collections.enumeration(arrayList);
System.out.println("Enumerating through Java ArrayList");
while (en.hasMoreElements()) {
System.out.println(en.nextElement());
}
end = System.nanoTime();
System.out.println("Taken taken in enumeration process: "
+ (end - start));
}
private static void useWhileLoop(Collection<String> myList) {
start = System.nanoTime();
Iterator<String> itr = myList.iterator();
while (itr.hasNext()) {
String str = itr.next();
System.out.println(str);
}
end = System.nanoTime();
System.out.println("Taken taken in useWhileLoop process: "
+ (end - start));
}
private static void useForLoop(Collection<String> myList) {
start = System.nanoTime();
for (Iterator<String> itr = myList.iterator(); itr.hasNext();) {
System.out.println(itr.next());
}
end = System.nanoTime();
System.out.println("Taken taken in useForLoopWithIterator process: "
+ (end - start));
}
public static void addElements() {
arrayList.add("C");
arrayList.add("A");
arrayList.add("E");
arrayList.add("B");
arrayList.add("D");
arrayList.add("F");
arrayList.add(1, "A2");
}
public static void main(String[] args) {
addElements();
iterator();
}
}
Surprisingly, the cycle executed by using for each cycle lags behind the simple cycle for the cycle . (Results may vary for different machines with different configurations.)
Console exit:
Taken taken in simpleForLoop process: 853200.0
Taken taken in forEachLoop process: 788993.0
Taken taken in useWhileLoop process: 452014.0
Taken taken in useForLoopWithIterator process: 299775.0
Taken taken in enumeration process: 766756.0
So why do people prefer to do this through a loop for everyone ? Is there a performance based reason?