http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html
그것은 설명이 예제에서 "표준 자바 반복자와 유사하며 InnerEvenIterator 내부 클래스." 그래서 반복기는 자바에서 꽤 흔한 일입니다.
나는 C 프로그래밍 배경에서 왔습니다. 나는 왜 이런 단순한 루프가 두 가지 방법으로 반복자 (내부 클래스)로 확장되었는지 이해할 수 없다. 여기에 무슨 요점이 있니?
public class DataStructure {
//create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
//fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
//print out values of even indices of the array
InnerEvenIterator iterator = this.new InnerEvenIterator();
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
//inner class implements the Iterator pattern
private class InnerEvenIterator {
//start stepping through the array from the beginning
private int next = 0;
public boolean hasNext() {
//check if a current element is the last in the array
return (next <= SIZE - 1);
}
public int getNext() {
//record a value of an even index of the array
int retValue = arrayOfInts[next];
//get the next even element
next += 2;
return retValue;
}
}
public static void main(String s[]) {
//fill the array with integer values and print out only values of even indices
DataStructure ds = new DataStructure();
ds.printEven();
}
}
인덱스를 통해 무언가를 찾는 것이 비용이 많이 들지만 요소에서 다음 단계로 이동하는 것은 저렴합니다 (예 : 긴 링크 된 목록). 루프의 성능과 반복기의 성능을 비교합니다. –
또는 예를 들어 next() 메서드에서 필요에 따라 콘텐츠 데이터를 가져 오는 경우와 같이 목록의 크기를 실제로 알지 못하는 경우입니다. 이 경우 Iterator 추상화는 크기를 확인하기 위해 처음부터 전체 데이터 세트를 가져올 필요가 없음을 의미합니다. – Ash