- Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
- Method names have been improved.
Methods:
1.hasNext
- public boolean hasNext()
- Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.)
- Returns the next element in the iteration.
-
- Returns:
- the next element in the iteration.
- Throws:
NoSuchElementException
- iteration has no more elements- 3.remove
public void remove()
- Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
-
- Throws:
UnsupportedOperationException
- if the remove operation is not supported by this Iterator.IllegalStateException
- if the next method has not yet been called, or the remove method has already been called after the last call to the next method
Example:
/*Iterate through a Collection using Java Iterator Example
- This Java Example shows how to iterate through a Collection using Java Iterator.
- */
- import java.util.Iterator;
- import java.util.ArrayList;
- public class JavaIteratorExample {
- public static void main(String[] args) {
- //create an ArrayList object
- ArrayList aList = new ArrayList();
- //populate ArrayList object
- aList.add("1");
- aList.add("2");
- aList.add("3");
- aList.add("4");
- aList.add("5");
- /*
- Get Iterator object by invoking iterator method of collection.
- Iterator provides hasNext() method which returns true if has more
- elements. next() method returns the element in iteration.
- */
- Iterator itr = aList.iterator();
- //iterate through the ArrayList values using Iterator's hasNext and next methods
- while(itr.hasNext())
- System.out.println(itr.next());
- /*
- Please note that next method may throw a java.util.NoSuchElementException
- if iteration has no more elements.
- */
- }
- }
- /*
- Output would be
- 1
- 2
- 3
- 4
- 5
- */
2.next
public Object next()
No Response to "Interface Iterator"
Post a Comment