Sunday, 12 July 2015

Tutorial On Iterator In Java

Some times our program requires  to access to each element in collection classes for example our program require to print each element in a collection so java provide easiest way to do this by using iterator.

ITERATOR:

Iterator enables programmer to access each element in collection lists,iterator can be used to add or remove elements one  at a time its implements listiterator interface.Iterator is very applicable when dealing with large collections.

STEPS FOR ACCESSING ELEMENTS USING ITERATOR:

  • Iterator it = l1.iterator()
       In first step we need to obtain an iterator as shown above.

  • while(it.hasNext())
      Use while loop it will continue until the list elements have not finished.

  • next()
    Use next method to obtain  the next element of iteration and complete requirement of program.


OTHER USEFUL METHODS OF ITERATOR:

int previousIndex( )

This method is used to check index of previous index of iterator if there is no previous element it will return -1.

Ob previous( )

Use to return previous element of collection.

int nextIndex( )

Used to return the index(number) of next element in collection.

boolean hasPrevious( )

This method returns true if collection contains previous element.

void set(Object obj)

This method is  used to changed the value of specific object in the collection as shown in below program.

void remove( )


This method is used to remove current element from a list.


CODING:

import java.util.*;
class linkedlist
{
public static void main(String args[])
{
//Creating Linked List
LinkedList l1 = new LinkedList();
//Adding Elements To A Linked List
l1.add("No 2 Element");
l1.add("No 3 Element");
l1.add("No 4 Element");
l1.addFirst("No 1 Element");
l1.addLast("No 5 Element");
l1.add(5,"No 6 Elment");
Iterator it = l1.iterator();
while(it.hasNext())
{
Object obj = it.next();
System.out.println(obj);
}
ListIterator lit = l1.listIterator();
while(lit.hasNext())
{
Object obj1 = lit.next();
lit.set(obj1+"changed");
}
while(lit.hasPrevious())
{
Object obj1 = lit.previous();
System.out.println("Printing reverse List "+obj1);
}

}
}

OUTPUT:


No comments:

Post a Comment