# * Iterator, Iterable 차이점

Written by πŸ“ Bluemoon

Iterator, Iterable은 μžλ°” μ»¬λ ‰μ…˜ μΈν„°νŽ˜μ΄μŠ€μ—μ„œ 제곡

# Iterable

Iterable은 μˆœνšŒν•  수 μžˆλŠ” μ»¬λ ‰μ…˜μ„ λ‚˜νƒ€λ‚Έλ‹€. 이 μΈν„°νŽ˜μ΄μŠ€λ₯Ό μƒμ†ν•˜κ²Œ 되면 κ°μ²΄λŠ” for-each loopλ₯Ό μ‚¬μš©ν•  수 있게 ν•΄μ€€λ‹€.
(λ‚΄λΆ€μ μœΌλ‘œ iterator() λ©”μ†Œλ“œλ₯Ό 객체에 ν˜ΈμΆœν•΄μ„œ κ°€λŠ₯)

List <String> persons = new ArrayList<>(Arrays.asList("A", "B", "C"));
for (String person: persons) {
    System.out.println(person);
}
1
2
3
4

μœ„μ˜ μ˜ˆμ œμ—μ„œ μ‚¬μš©λœ ListλŠ” Collection μΈν„°νŽ˜μ΄μŠ€λ‘œ μ°Ύμ•„ κ°€κ²Œλ˜λ©΄ μ•„λž˜μ™€ 같이 iterable μΈν„°νŽ˜μ΄μŠ€λ₯Ό μƒμ†ν•˜κ³  μžˆλ‹€.

public interface Collection<E> extends Iterable<E> {
    ...
1
2

# Iterator

Iterator μΈν„°νŽ˜μ΄μŠ€λŠ” λ‹€λ₯Έ 객체, λ‹€λ₯Έ μ’…λ₯˜μ˜ μ»¬λ ‰μ…˜μ„ μˆœνšŒν•˜κ²Œ ν•΄μ€„μˆ˜ μžˆλ‹€. 이 μΈν„°νŽ˜μ΄μŠ€λ₯Ό μˆœνšŒν•˜κΈ° μœ„ν•΄μ„œλŠ” hasNext() + next() λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•΄μ•Όν•œλ‹€.

Iterator <Integer> iterator = Arrays.asList(1, 2, 3, 4, 5).iterator();
while (iterator.hasNext()) {
            System.out.println(iterator.next());
}
1
2
3
4

Collection μΈν„°νŽ˜μ΄μŠ€λ₯Ό 보면 Iterator μΈν„°νŽ˜μ΄μŠ€λ₯Ό λ©”μ†Œλ“œλ₯Ό λ§Œλ“€μ–΄ μ‚¬μš©ν•˜κ³  μžˆλŠ”κ±Έ λ³Ό 수 μžˆλ‹€.

Iterator<E> iterator();
1

for-each loopμ—μ„œ λžŒλ‹€λ₯Ό μ‚¬μš©ν•΄μ„œ Iterable μ•ˆμ˜ Iterator둜 μ»¨λ²„νŒ…μ„ ν•  수 μžˆλ‹€.

for (Integer i: (Iterable<Interger>) () -> iterator) {
    System.out.println(i);
}
1
2
3
Last Updated: 8/19/2019, 2:50:10 AM