Jump to content

Java - Loop differences ?

Go to solution Solved by elpiop,

A for-each construct has an iterator 'under the hood' so to speak, however you are unable to remove objects from collections using such a loop. Since it hides the iterator, the foreach loop has the advantage of improved readability. If you instead write your own iterator, you are then able to modify the collection while you are iterating through it (this is not possible with the other loops). 

 

While loops are useful when you need to run code until a certain condition is met.

 

 

 

Hi,

 

I've just learnt for-each loops and while loops in Java... What's an iterator exactly and how's it different from the other two??? Is an iterator only for objects? 

By iterator I mean the one that uses hasnext, next and remove functions. Thanks in advance! (very confused student here) 

Link to comment
Share on other sites

Link to post
Share on other sites

A for-each construct has an iterator 'under the hood' so to speak, however you are unable to remove objects from collections using such a loop. Since it hides the iterator, the foreach loop has the advantage of improved readability. If you instead write your own iterator, you are then able to modify the collection while you are iterating through it (this is not possible with the other loops). 

 

While loops are useful when you need to run code until a certain condition is met.

 

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

44 minutes ago, elpiop said:

A for-each construct has an iterator 'under the hood' so to speak, however you are unable to remove objects from collections using such a loop. Since it hides the iterator, the foreach loop has the advantage of improved readability. If you instead write your own iterator, you are then able to modify the collection while you are iterating through it (this is not possible with the other loops). 

 

While loops are useful when you need to run code until a certain condition is met.

 

 

 

Thanks for answering my questions once again :)

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×