기타/What I Learned

[TIL] 자료구조 - 반복자

가죽방패 2022. 3. 30. 10:27

※ 반복자

- 배열의 각각의 원소를 출력할 때, 다음과 같이 코드를 작성할 수 있다

int arr[] = {1, 2, 3, 4, 5};
for (int i=0; i<arr.length; i++){
	system.out.println(arr[i]);
}

혹은 다음과 같이 작성이 가능하다

int arr[] = {1, 2, 3, 4, 5};
for(int x:arr){
	system.out.println(x);
}

하지만 객체에서 두 번째 방식으로 반복문이 동작하기 위해선 Iterator 인터페이스를 구현해야 하는데 Iterator 인터페이스 구현 코드의 예시는 다음과 같다.

public Iterator<E> iterator(){
	return new IteratorHelper();
}

public class LinkedList<E> implements Listl<E>{
	class IteratorHelper implement Iterator<E>{
    	Node<E> index;
        public IteratorHelper(){
        	index = head;
        }
        public boolean hasNext(){
        	return (index != null)
        }
        public E next(){
        	if(!hasNext())
            	throw new NoSuchElementException();
            E val = index.data;
            index = index.next;
            return val;
        }
    }
}