※ 반복자
- 배열의 각각의 원소를 출력할 때, 다음과 같이 코드를 작성할 수 있다
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;
}
}
}
'기타 > What I Learned' 카테고리의 다른 글
[TIL] 자료구조 - 원형 연결 리스트 (0) | 2022.04.01 |
---|---|
[TIL] 자료구조 - 이중 연결 리스트 (0) | 2022.03.31 |
[TIL] 자료구조 - 연결리스트 테스트 (0) | 2022.03.29 |
[TIL] 자료구조 - peek 메소드 (0) | 2022.03.28 |
[TIL] 자료구조 - remove, find (0) | 2022.03.25 |