이 글은 java 언어로 배우는 디자인 패턴 입문을 읽고 작성한 글입니다.
Iterable< T >
public interface Iterable<T> {
Iterator<T> iterator();
}
Iterator< E >
java.util패키지에 Iterator 인터페이스로 선언되어 있다.
Iterator는 집합체의 요소를 순회하며 처리를 반복하게 해주는 인터페이스다.
E는 데이터 집합의 타입을 의미한다.
public interface Iterator<E> {
boolean hasNext();
E next();
}
Main
hasNext(): 컬랙션을 순회하면서 다음 요소가 있는지 판단해주는 메서드
next(): 다음 요소를 가져오는 메서드로, 다음요소를 가져오면 그 다음 요소를 가져올 준비까지 한다.
Book
public class Book{
private String name;
public Book(String name){
this.name = name;
}
public String getName(){
return name;
}
}
BookShelf
Book클래스에서 만든 인스턴스들을 담기위한 클래스다.
iterator()메서드는 BookShelfIterator클래스의 인스턴스를 만들어주는 메서드다.
public class BookShelf implement Iterable<BooK>{
private Book[] books;
private int last = 0;
public BookShelf(int maxSize) {
books = new Book[maxSize];
}
public Book getBookAt(int index){
return books[index];
}
public void appendBook(Book book){
books[last] = book;
last++;
}
public int getLength(){
return last;
}
@Override
public Iterator<Book> iterator(){
return new BookShelfIterator(this);
}
}
BookShelfIterator
public class BookShelfIterator implements Iterator<Book> {
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf = bookShelf;
}
@Override
public boolean hasNext() {
if(index<bookShelf.getLength()){
return true;
}
else return false;
}
@Override
public Book next(){
if(!hasNext()){
throw new NoSuchElementException();
}
Book book = bookShelf.getBookAt(index++);
return book;
}
}
Main
package iteratorTest.book;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
BookShelf bookShelf = new BookShelf(10);
bookShelf.appendBook(new Book("Computer Network"));
bookShelf.appendBook(new Book("Operating System"));
bookShelf.appendBook(new Book("Oriented Programming"));
bookShelf.appendBook(new Book("C Programming"));
Iterator<Book> it = bookShelf.iterator();
while(it.hasNext()) {
Book book = it.next();
System.out.println(book.getName());
}
System.out.println();
for(Book book : bookShelf){
System.out.println(book.getName());
}
System.out.println();
}
}