Using an Iterator to iterate all elements in an ArrayList - Java Collection Framework

Java examples for Collection Framework:ArrayList

Introduction

An iterator object implements the Iterator interface, which is defined as part of the java.util package.

The Iterator Interface

Method Explanation
hasNext() Returns true if the collection has at least one element that hasn't yet been retrieved.
next()Returns the next element in the collection.
remove() Removes the most recently retrieved element.

Demo Code

import java.util.ArrayList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {

    ArrayList<String> nums = new ArrayList<String>();
    nums.add("One");
    nums.add("Two");
    nums.add("Three");
    nums.add("Four");

    String s;//  w ww  .  jav a 2 s  . c o m
    Iterator e = nums.iterator();
    while (e.hasNext()) {
      s = (String) e.next();
      System.out.println(s);
    }

  }

}

Related Tutorials