
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterator vs ForEach in Java
Collections can be iterated easily using two approaches.
Using for-Each loop − Use a foreach loop and access the array using object.
Using Iterator − Use a foreach loop and access the array using object.
Differences
ConcurrentModificationException − Using for-Each loop, if an object is modified, then ConcurrentModificationException can occur. Using iterator, this problem is elliminated.
Size Check − Using for-Each, size check is not required. Using iterator if hasNext() is not used properly, NoSuchElementException can occur.
Performance − Performance is similar for both cases.
Following is an example of using above ways.
Example
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Tester { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1);list.add(2);list.add(3); list.add(4);list.add(5);list.add(6); System.out.println("List: "); //Way 1: for (int i : list) { System.out.print(i + " "); } Iterator<Integer> listIterator = list.iterator(); System.out.println("\nList: "); while(listIterator.hasNext()){ System.out.print(listIterator.next() + " "); } } }
Output
List: 1 2 3 4 5 6 List: 1 2 3 4 5 6
Advertisements