|

Retrieving elements from collections

Following four ways are used to retrieve elements from collection object :

Using for-each loop.

Using Iterator Interface.

Using ListIterator interface.

Using Enumeration Interface.

For-each loop :

for-each loop is like for loop which repeatedly executes a group of statements,for each element of collection

the format is

for(variable:collection object)  // for( String values: os)

{

statements;

}

if the collection object having  N number of elements then loop repeats N times,

each time variable stores value of the object from the collection object.

 

Example:

 

{code}

 

HashSet<String>  hs=new HashSet<String>();

hs.add(“vijay”);

hs.add(“kumar”);

hs.add(“katta”);

for(String value:hs)

{

System.out.println(“ value: “+value);

// statements

}

}

{code}

 

out put format :

here you can observe clearly that  for loop reads the values from the hashset from the reverse order

i.e  in the above code i added in the vijay kumar katta  sequence to the hashset but while reading it displays

katta kumar vijay  , here it follows LIFO (last in first out) .

 

Iterator Interface :

now we see reading the values from the collection object using Iterator interface.

this iterator interface having three methods to retrieve the elements one by one from a collection object.

boolean hasNext();

this method returns true if the iterator has more elements.

element next()

this method returns the next element  in the iterator.

void remove();

this method removes the element from the collection  , the last element which is returned by the iterator.

 

Example:

HashSet<String> hs=new HashSet<String>();

hs.add(“vijay”);

hs.add(“kumar”);

hs.add(“katta”);

Iterator it=hs.iterator();

while(it.hasNext())

{

System.out.println(“value:”+it.next());

}

it.remove();      // removing last element ( katta) from the collection

ListIterator Interface :

it is an interface that contains methods to retrieve elements from collection object , in both forward and reverse directions.

methods are :

boolean hasNext() ;

this returns true if the listiterator has more elements when traversing in the forward direction.

boolean hasPrevious();

this returns true if the listiterator has more elements when traversing the list in reverse direction.

element next()

this returns the next element in the list.

element previous()

this returns the previous element in the list.

void remove()

this removes the element from the list , the last element returned by the next() or previous()

 

Enumeration Interface :

this interface used to retrieve the elements  one by one from the list like Iterator , it has 2 methods

        boolean hasMoreElements()

       this method tests if the enumeration has any more elements or not.

      element nextElement()

this returns next element which was available in the enumeration. 

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *