티스토리 뷰

Java

Iterator Pattern

techbard 2016.07.18 16:57

Iterator.zip



# 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



댓글
댓글쓰기 폼
공지사항
Total
394,934
Today
5
Yesterday
28
«   2018/11   »
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30  
글 보관함