Here is a very good example on how to use the Iterator, for and foreach-loop in Java:
import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class JavaApplication { public static void main(String[] args) throws IOException { List<String> names = new ArrayList<>(); names.add("Benny"); names.add("Sarah"); names.add("Daniel"); names.add("Maria"); // Iterator Iterator<String> iterator = names.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } // for for (int i = 0; i < names.size(); i++) { System.out.println(names.get(i)); } // foreach for (String name : names) { System.out.println(name); } } } |