java에서 Iterator가 뭘까?
Iterator (반복자)
반복적인 작업을 수행하는 것.
- Main.java
public class Main{
public static void main(String[] args){
ArrayList numbers = new ArrayList();
numbers.addLast(10);
numbers.addLast(20);
numbers.addLast(30);
numbers.addLast(40);
for(int i=0;i<numbers.size();i++){
System.ot.println(numbers.get(i));
}
ArrayList.ListIterator li = numbers.listIterator();
//numbers 객체의 반복적인 작업 수행을 위해서는 ArrayList의 ListIterator라는 객체가 필요
while(li.hasNext()){
System.out.println(li.next());
}
//10 20 30 40 print됨
while(li.hasPrevious()){
System.out.println(li.previous());
}
//40 30 20 10 print됨
}
- ArrayList.java
public Object removeFirst(){
return remove(0);
}
public Object removeLast(){
return remove(size-1);
}
public Object get(int index){
return elementData[index];
}
public int size(){
return size;
}
public int indexOf(Object o){
for(int i=0 ; i<size ; i++){
if(o.equals(elementData[i])){
return i;
}
return -1;
}
}
public ListIterator listIterator(){
return new ListIterator();
}
class ListIterator{
private int nextIndex = 0;
public boolean hasNext(){
return nextIndex < size();
}
public Object next(){
return elementData[nextIndex++];
}
public boolean hasPrevious(){
return nextIndex > 0;
}
public Object previous(){
return elementData[--nextIndex];
}
public void add(Object element){
ArrayList.this.add(nextIndex++, element);
//element를 넣을 index인 nextIndex를 매개변수로 넣어주고,
//element를 넣은 후 nextIndex를 1 증가시켜줌.
}
public void remove(){
ArrayList.this.remove(nextIndex-1);
nextIndex--;
}
}