Tuesday, October 7, 2014

ArrayList Loop (for, Iterator, ListIterator)


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

// Iterator vs ListIterator
// 1. Iterator traverse List and Set; ListIterator traverse List
// 2. Iterator can go next; ListIterator can go next and previous
// 3. Iterator can not get Index; ListIterator can get Index
// 4. Iterator can NOT add item when traverse; ListIterator can add when traverse
// 5. Iterator can NOT replace item when traverse; ListIterator can replace when traverse


public class ArrayListTest {
   
    public static void main(String[] args){
       
        List<String> list = new ArrayList<String>();
        list.add("A");
        list.add("B");
        list.add("C");
       
        // use enhanced for to loop
        for (String str : list){
            System.out.println(str);
        }
       
        // use Iterator to loop
        Iterator it = list.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
       
        // use ListIterator to loop
        ListIterator li = list.listIterator();
        while (li.hasNext()){
            System.out.println(li.next());
        }
               
    }

}


OUTPUT:

A
B
C
A
B
C
A
B
C

No comments:

Post a Comment