---
title: "Limitations of for-each loop"  
description: "Limitations of for-each loop"  
author: "Jonas Stuart"  
published: 2016-07-12  
updated: 2016-07-21  
canonical: https://www.mindstick.com/forum/34152/limitations-of-for-each-loop  
category: "java"  
tags: ["java"]  
reading_time: 2 minutes  

---

# Limitations of for-each loop

HI buddy\
Can [someone tell me](https://www.mindstick.com/forum/34097/can-someone-tell-me-what-is-the-most-effective-optimization-on-page-optimization-or-off-page-optimization) [Limitations](https://www.mindstick.com/interview/121/what-are-the-benefits-and-limitations-of-using-hidden-fields) of for-each loop.I would really appreciate your help.\
thanks

## Replies

### Reply by Abhishek Singh

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.\


---

Original Source: https://www.mindstick.com/forum/34152/limitations-of-for-each-loop

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
