CodesJava

Easy learning with example program codes

how to display arraylist values by using iterator in java?


ArrayList:

ArrayList class extends AbstractList and implements the List interface. It uses dynamic arrays for storing elements. It maintains insertion order. ArrayList can contain duplicate elements. It is not synchronized.
Note: ArrayList provides the facility of random access because of it is index based.

We can use iterator interface. It is a universal iterator as we can apply it to any Collection object. It provides the functionality of read and remove operations. Collection interface provides iterator() method to get the Iterator object. Iterator interface have following to methods to iterate collection objects.

hasNext(): It returns true if the iteration has more elements.
next(): It returns the next element in the iteration.

Example:

package com.codesjava;
 
import java.util.ArrayList;
import java.util.Iterator;
 
public class Test {
  public static void main(String args[]){
	ArrayList<String> list = new ArrayList<String>();
	list.add("Jai");
	list.add("Mahesh");
	list.add("Vivek");
	list.add("Naren");
	list.add("Hemant");
	list.add("Vishal");
        Iterator<String> iterator = list.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
  }
}

Output:

Jai
Mahesh
Vivek
Naren
Hemant
Vishal
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki