# Item.java
import java.util.Iterator;
public class Item implements Iterable<String> {
private String[] items;
private int index;
public Item() {
this.items = new String[10];
this.index = 0;
}
public void add(String item) {
if (index == items.length) {
String[] largerItems = new String[items.length + 5];
System.arraycopy(items, 0, largerItems, 0, items.length);
items = largerItems;
largerItems = null;
}
items[this.index] = item;
this.index++;
}
@Override
public Iterator<String> iterator() {
Iterator<String> itr = new Iterator<String>() {
private int currentIndex = 0;
@Override
public boolean hasNext() {
return currentIndex < items.length && items[currentIndex] != null;
}
@Override
public String next() {
return items[currentIndex++];
}
};
return itr;
}
}
# Main.java
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
Item item = new Item();
item.add("a");
item.add("b");
item.add("c");
Iterator<String> itemIterator = item.iterator();
while (itemIterator.hasNext()) {
System.out.println(itemIterator.next());
}
}
}
# 결과
a
b
c
댓글 영역