Home > DeveloperSection > Forums > Limitations of for-each loop
Jonas Stuart
Jonas Stuart

Total Post:11

Posted on    July-12-2016 8:12 AM

 Java Java 

 1 Reply(s)
 228  View(s)
Rate this:
HI buddy

Can someone tell me Limitations of for-each loop.I would really appreciate your help.


Abhishek Singh

Total Post:8

Posted on    July-21-2016 3:27 AM

for each loop provides a way to iterate over a collection of objects of class implementing Iterable interface. It provides little better performance as compared to traditional for loop and is a cleaner way to iterate over a collection. It removes the chances of error that could be introduced while iterating over multiple collection through traditional for loop . Developer could got wrong in updating and traversing over changing indexes of objects in collection . This kind of error is unlikely in for each loop

But there are situations where for-each can't be used 

1. If you want to remove an element of collection while iterating for-each provides no remove method. So you can't use it in such scenario

2. If you want to replace some element in collection while iterating over collection You can't do that as there is no replace or update method here neither you have control to access the element with its index value .

3.A situation where you are working in parallel with multiple collections have to do a lot of operation with current index value of iterable collection. You don't have access to element index while iterating with for-each loop So you can't use it.

Don't want to miss updates? Please click the below button!

Follow MindStick