As I’m coding and discovering new ways of doing things in Java, I’m always somewhat perplexed in the better method of looping through lists to output data.
In the following example, I’m looping through lists and using a counter, so many times I’ve had to include an index counter in the output.
I'm partial to Method 1 but I found any of these method a bit dated. I’ve seen many examples of looping through lists and Method 2 is mostly used.
So my question is what is the better method, if all of these methods are just as equal, then what is the most standard?
private ArrayList<String> list = new ArrayList<String>();
public Test() {
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
list.add("Five");
method1();
method2();
method3();
}
public void method1() {
System.out.println("Method 1");
int i = 1;
for (String value:list) {
System.out.println((i++) + " = " + value);
}
}
public void method2() {
System.out.println("Method 2");
for (int i = 0; i < list.size(); i++) {
System.out.println((i+1) + " = " + list.get(i));
}
}
public void method3() {
System.out.println("Method 3");
Iterator<String> it = list.iterator();
int i = 1;
while (it.hasNext()) {
System.out.println((i++) + " = " + it.next());
}
}