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?
for() loop can always be replaced with while() loop, but sometimes, you cannot use for() loop and while() loop must be used.
The issue with your while loop not closing is because you have an embedded for loop in your code. What happens, is your code will enter the while loop, because while(test) will result in true . Then, your code will enter the for loop. Inside of your for loop, you have the code looping from 1-10.
in general a while loop is used if you want an action to repeat itself until a certain condition is met i.e. if statement. An for loop is used when you want to iterate through an object. i.e. iterate through an array.
This is what it wants you to use:
for (Object o : list) { System.out.println(o.toString()); }
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()
).
Because you are less likely to make mistakes and it looks better ; )
for( Object obj : list ) { System.out.println( obj.toString() ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With