Java Iterator

In this post, I will talk about Java iterator which is a powerful tool for us to traverse elements. In addition, enhanced for loop will also be introduced which can simplify the code for element traversal.


Introduction

JDK provides us with an interface java.util.Iterator to iterate through elements in a collection. This is because the ways of traversing elements are different.

Iterator checks if there are elements in a collection first. If there exists elements, iterator will take out that element. Iterator works by repeating this process until there is no element in the collection. This process is called iteration.


How to use iterator

private static void demo01() {
    // 1: Create the iterator object
    Collection<String> coll = new ArrayList<>();
    coll.add("Jason");
    coll.add("Kevin");
    coll.add("Larry");
    Iterator<String> it = coll.iterator();

    // 2: hasNext() checks if there are elements left
    while (it.hasNext()) {
        // 3: next() takes out the next element of the collection
        System.out.println(it.next()); // Jason Kevin Larry
    }
}

How iterator works

When an iterator is created, it points to the index ‘-1’. ’next()’ method takes out the next element and moves the iterator to the next position.


Enhanced For Loop

Enhanced for loop uses iterators to simplify the traditional way of using iterators. However, enhanced for loop can only traverse elements. No other operations can be made.

// Using enhanced for loop to traverse array
private static void demo01() {
    int[] arr = {1, 2, 3, 4, 5};
    for (int i : arr) System.out.println(i);
}

// Using enhanced for loop to traverse collection
private static void demo02() {
    ArrayList<String> list = new ArrayList<>();
    list.add("aaa");
    list.add("bbb");
    list.add("ccc");
    for (String s : list) System.out.println(s);
}