standard-library-in-x

Notes and readings for STL workshop

View on GitHub

Iterators in JAVA

For example.

  
 ArrayList<Integer> al=new ArrayList<>();     //Collection declaration
 
 al.add(2); al.add(3); al.add(4);             // populating data
 
 for(Integer x: al){
 
 System.out.println(x);
 
 }
 

Output

 2
 
 3
 
 4

collection of objects.

Iterator is like pointer which points to location.

In this section, we will discuss about Java Iterator methods in-brief. We will explore these methods in-depth with some useful examples in the coming section.

Even Every Collection has iterator() method which returns reference of Iterator object which we can use to iterate over Collection.

Iterator object has .next() method which returns next element of collection and increments pointer.

hasNext() method which returns boolean value which represents existence of next element in collection.

So by using both the methods we can iterate over collection.

For example.

  
 ArrayList<Integer> al=new ArrayList<>();   //Collection declaration
  
  al.add(2); al.add(3); al.add(4);       // populating data
 
 Iterator<Integer> it=al.iterator();         //  '<>'  these Brackets should contain type of objects you have added in Collection 
 
 while(it.hasNext()){
  Integer x=it.next();
  System.out.println(x);
 }
 

Output

 2
 
 3
 
 4

Normal Iterator object can only be incremented but ListIterator Object can be decremented as well.

Hence it is most powerful iterator object.

hasPrevious() and previous() have similar meaning as hasNext() and next() methods.

public interface ListIterator <E> extends Iterator<E>

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain

the iterator’s current position in the list. A ListIterator has no current element; its cursor position always lies between the element

that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of

Note that the remove() and set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last

element returned by a call to next() or previous().

This interface is a member of the Java Collections Framework.

 
   
 ArrayList<Integer> al=new ArrayList<>();   //Collection declaration
  
  al.add(2); al.add(3); al.add(4);       // populating data
 
 ListIterator<Integer> it=al.listIterator();         //  '<>'  these Brackets should contain type of objects you have added in Collection 
 
 while(it.hasNext()){
  Integer x=it.next();
  if(it.hasPrevious()){
  	Integer y=it.previous();
  	System.out.println("Previous "+y);
  }
  it.next();
  System.out.println("Next "+x);

 }
 

Output

Previous 2

Next 2

Previous 3

Next 3

Previous 4

Next 4