Accessing a Collection
To access, modify or remove any element from any collection we need to first find the element, for which we have to cycle throught the elements of the collection. There are three possible ways to cycle through the elements of any collection.
- Using Iterator interface
- Using ListIterator interface
- Using for-each loop
Accessing elements using Iterator
Iterator Interface is used to traverse a list in forward direction, enabling you to remove or modify the elements of the collection. Each collection classes provide iterator() method to return an iterator.
import java.util.*;
class Test_Iterator
{
public static void main(String[] args)
{
ArrayList< String> ar = new ArrayList< String>();
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
Iterator it = ar.iterator(); //Declaring Iterator
while(it.hasNext())
{
System.out.print(it.next()+" ");
}
}
}
Output :
ab bc cd de
Accessing element using ListIterator
ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only those collections that implement the List Interface.
import java.util.*; class Test_Iterator { public static void main(String[] args) { ArrayList< String> ar = new ArrayList< String>(); ar.add("ab"); ar.add("bc"); ar.add("cd"); ar.add("de"); ListIterator litr = ar.listIterator(); while(litr.hasNext()) //In forward direction { System.out.print(litr.next()+" "); } while(litr.hasPrevious()) //In backward direction { System.out.print(litr.next()+" "); } } }
Output :
ab bc cd de de cd bc ab
Using for-each loop
for-each
version of for loop can also be used for traversing each element of a collection. But this can only be used if we don't want to modify the contents of a collection and we don't want any reverse access. for-each
loop can cycle through any collection of object that implements Iterable interface.import java.util.*; class ForEachDemo { public static void main(String[] args) { LinkedList< String> ls = new LinkedList< String>(); ls.add("a"); ls.add("b"); ls.add("c"); ls.add("d"); for(String str : ls) { System.out.print(str+" "); } } }
Output :
a b c d
No comments:
Post a Comment