Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ suggests replacing the while loop with a for each loop. Why?

Tags:

    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?

like image 645
InvalidBrainException Avatar asked Oct 11 '11 15:10

InvalidBrainException


People also ask

Can for loop replace while loop?

for() loop can always be replaced with while() loop, but sometimes, you cannot use for() loop and while() loop must be used.

Why does my do while loop not stop?

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.

How we can use while loop in place of for loop?

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.


2 Answers

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()).

like image 61
Jim Garrison Avatar answered Nov 27 '22 15:11

Jim Garrison


Because you are less likely to make mistakes and it looks better ; )

for( Object obj : list ) {   System.out.println( obj.toString() ); } 
like image 34
MasterCassim Avatar answered Nov 27 '22 15:11

MasterCassim