Iterator is an interface introduced in java 1.2 version. It is used to retrieve the elements one by one from a collection object.By iterating the elements we can perform remove operation also in addition to read operation. In addition to the Collection interfaces ,collections also use iterator and ListIterator interfaces we will discuss in depth about ListIterator interface in the next article.Now will understand the iterator interface.
Each of the collection classes provides an iterator()method that returns to the start of the collection. By using iterator object you can access each element in the collection one element at a time. we can use iterator() method in ArrayList, LinkedList,HashSet,Set,Map.So the main purpose of iterator interface is retrieving elements from Collections.
This interface contains the fallowing 3 methods:
1) boolean hasNext();//this method returns true if the iterator has more elements
2) Object next();//This method returns next element in the iterator
3)void remove();//This method removes from the collection the last element returned by the iterator.
Example:
public interface Iterator<E>
{
E next();
boolean hasNext();
void remove();
}
By repeatedly calling next() method , you can visit the elements from the collection one by one.After reaching the end of the collection,then next method throws NoSuchElementException. Thus, you need to call hasNext() method before calling next(). It(hasNext()) returns true if iterator object has more elements to visit.
The fallowing example demonstrating iterator interface. It uses ArrayList object,but general principles apply to any collection.
import java.util.*;
class IteratorDemo
{
public static void main(String args[])
{
ArrayList<Integer> al=new ArrayList<Integer>(); //crating ArrayList for intergers
for(int i=0;i<=20;i++)
{
al.add(i);
}
System.out.println(al); //original content of al
//use iterator to display contents of al
Iterator itr=al.iterator();
while(itr.hasNext())
{
Integer i=(Integer)itr.next();
if(i%2==0)
{
System.out.println(i);
}
else
{
itr.remove();
}
}
System.out.println(al);
}
}
Output:
E:\>javac IteratorDemo.java
E:\>java IteratorDemo
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
0
2
4
6
8
10
12
14
16
18
20
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Iterator always moves forward direction only that means single direction whereas ListIterator can move forward and backword direction we will discuss next article.
By using iterator we can perform both read and remove operation already we have seen in the above example. We can not perform any replace or adding new object to the list.
To overcome all these above limitations then we should choose ListIterator interface.
for-each loop:
The for-each loop is used to alternative to iterators. It is just like for loop which executes repeatedly a group of statements for each element of the collection.If you don't want modifying the contents of collection or obtaining elements in reverse order then for-each version of the for loop is most convenient way to retrieve elements from collections instead of iterator.
Syntax:
for(variable: collection-object)
{
Statements;
}
In the above syntax variable represents each element of the collection object and the loop is executed as many times as there are number of elements in the collection object.
Example:
import java.util.*;
class ForEachDemo {
public static void main(String args[]) {
// Create an array list for integers.
ArrayList<Integer> al = new ArrayList<Integer>();
// Add values to the array list.
al.add(5);
al.add(15);
al.add(25);
al.add(35);
al.add(45);
// Use for loop to display the values.
System.out.print("Original contents of vals: ");
for(int v : al)
System.out.print(v +" ");
System.out.println();
// Now, sum the values by using a for loop.
int sum = 0;
for(int v : al)
sum =sum+ v;
System.out.println("Sum of values: " + sum);
}
}
Output:
E:\>javac ForEachDemo.java
E:\>java ForEachDemo
Original contents of vals: 5 15 25 35 45
Sum of values: 125
Each of the collection classes provides an iterator()method that returns to the start of the collection. By using iterator object you can access each element in the collection one element at a time. we can use iterator() method in ArrayList, LinkedList,HashSet,Set,Map.So the main purpose of iterator interface is retrieving elements from Collections.
This interface contains the fallowing 3 methods:
1) boolean hasNext();//this method returns true if the iterator has more elements
2) Object next();//This method returns next element in the iterator
3)void remove();//This method removes from the collection the last element returned by the iterator.
Example:
public interface Iterator<E>
{
E next();
boolean hasNext();
void remove();
}
By repeatedly calling next() method , you can visit the elements from the collection one by one.After reaching the end of the collection,then next method throws NoSuchElementException. Thus, you need to call hasNext() method before calling next(). It(hasNext()) returns true if iterator object has more elements to visit.
The fallowing example demonstrating iterator interface. It uses ArrayList object,but general principles apply to any collection.
import java.util.*;
class IteratorDemo
{
public static void main(String args[])
{
ArrayList<Integer> al=new ArrayList<Integer>(); //crating ArrayList for intergers
for(int i=0;i<=20;i++)
{
al.add(i);
}
System.out.println(al); //original content of al
//use iterator to display contents of al
Iterator itr=al.iterator();
while(itr.hasNext())
{
Integer i=(Integer)itr.next();
if(i%2==0)
{
System.out.println(i);
}
else
{
itr.remove();
}
}
System.out.println(al);
}
}
Output:
E:\>javac IteratorDemo.java
E:\>java IteratorDemo
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
0
2
4
6
8
10
12
14
16
18
20
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Iterator always moves forward direction only that means single direction whereas ListIterator can move forward and backword direction we will discuss next article.
By using iterator we can perform both read and remove operation already we have seen in the above example. We can not perform any replace or adding new object to the list.
To overcome all these above limitations then we should choose ListIterator interface.
for-each loop:
The for-each loop is used to alternative to iterators. It is just like for loop which executes repeatedly a group of statements for each element of the collection.If you don't want modifying the contents of collection or obtaining elements in reverse order then for-each version of the for loop is most convenient way to retrieve elements from collections instead of iterator.
Syntax:
for(variable: collection-object)
{
Statements;
}
In the above syntax variable represents each element of the collection object and the loop is executed as many times as there are number of elements in the collection object.
Example:
import java.util.*;
class ForEachDemo {
public static void main(String args[]) {
// Create an array list for integers.
ArrayList<Integer> al = new ArrayList<Integer>();
// Add values to the array list.
al.add(5);
al.add(15);
al.add(25);
al.add(35);
al.add(45);
// Use for loop to display the values.
System.out.print("Original contents of vals: ");
for(int v : al)
System.out.print(v +" ");
System.out.println();
// Now, sum the values by using a for loop.
int sum = 0;
for(int v : al)
sum =sum+ v;
System.out.println("Sum of values: " + sum);
}
}
Output:
E:\>javac ForEachDemo.java
E:\>java ForEachDemo
Original contents of vals: 5 15 25 35 45
Sum of values: 125
No comments:
Post a Comment