Home  >  Core Java

Iterator Java Example

By Arvind Rai, August 16, 2013
java.util.Iterator iterates the elements in Collection Framework. Iterator has taken the place of Enumeration. Iterator has three elements

1. hasNext()- checks if elements are available.
2. next() - returns the value
3. remove()- removes the elements from the Collection.

Find the example below.

IteratorDemo.java
package com.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorDemo {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("A");
        list.add("B");
        list.add("C");
        System.out.println(list.size());
        Iterator itr = list.iterator();
        while(itr.hasNext()){
            String s = itr.next();
            System.out.println(s);
            if("C".equals(s)){
                itr.remove();
            }
        }
        System.out.println(list.size());
    }
}
 
Output
3
A
B
C
2
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us