ArrayList<Object> list = new ArrayList<Object>();
list.add(12);
list.add("Hello");
list.add(true);
list.add('c');
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
System.out.println(iterator.next().toString());
}
When I enter this Java code in IntelliJ IDEA, the code analysis feature suggests that I replace the while loop with a for each loop since I’m iterating on a collection. Why is this?
This is what it wants you to use:
This has been in the language since Java 1.5, and is the idiomatic pattern. You need the Iterator only if you need access to the iterator’s other methods (i.e.
remove()).