Java - Enhanced for (For-Each) Loop
Java SE 8 Documentation: The For-Each Loop
Enhanced for (For-Each) Loop
Java의 Enhanced for Loop는 Java 5에서 도입된 새로운 반복 구문
- 배열 또는
Iterable
인터페이스를 구현하는 클래스(java SE 17) - 코드를 간결하게, 가독성을 향상
기존의 for 루프와 비교
1
2
3
4
5
6
7
8
9
10
11
// 기존의 for 루프
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Enhanced for 루프 (foreach)
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
Iterator 사용 시 가독성
1
2
3
4
5
6
7
8
9
List suits = ...;
List ranks = ...;
List sortedDeck = new ArrayList();
// BROKEN - throws NoSuchElementException!
for (Iterator i = suits.iterator(); i.hasNext(); )
for (Iterator j = ranks.iterator(); j.hasNext(); )
sortedDeck.add(new Card(i.next(), j.next()));
여기서 하위 반복문의 i.next()
호출이 너무 많고 가독성이 떨어진다.
1
2
3
for (Suit suit : suits)
for (Rank rank : ranks)
sortedDeck.add(new Card(suit, rank));
Java SE 8 Documentation: The For-Each Loop The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel.
This post is licensed under CC BY 4.0 by the author.