Accessing A Java Collection Via A Iterator
Accessing A Java Collection Via A Iterator
The java collection framework often we want to cycle through the elements. For example, we might want to display
each element of a collection. The java provides an interface Iterator that is available inside the java.util package to
We use the following steps to access a collection of elements using the Iterator.
Step - 2: Use the method hasNext( ) to access to check does the collection has the next element. (Use a
loop).
Step - 3: Use the method next( ) to access each element from the collection. (use inside the loop).
Method Description
boolean hasNext( ) Returns true if the collection has the next element, otherwise, it returns false.
class Demo
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
while(it.hasNext())
System.out.print(it.next()+" ");
Method Description
boolean hasNext( ) Returns true if the list collection has next element, otherwise it returns false.
boolean Returns true if the list collection has previous element, otherwise it returns false.
hasPrevious( )
int nextIndex( ) Returns the index of the next element. If there is no next element, returns the size of
the list.
E previousIndex( ) Returns the index of the previous element. If there is no previous element, returns -1.
{
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
System.out.print(litr.next()+" ");
System.out.print(litr.previous()+" ");