Java


Java Tutorial


Admission Enquiry Form

  

Retrieving Elements from Collections in Java



Retrieving Elements from Collections

  1. Using for-each loop
  2. Using Iterator inteface
  3. Using ListIterator interface





for-each Loop

for-each loop is like for loop which repeatedly executes a group of statements for each element of collection.The syntax of for-each loop is:

for(variable: collection-object)
{
Statements;
}

Note: Here, the variable assumes each element of the collection-object and the loop is executed as many times as there are number of elements in the collection-object.






Iterator Interface

Iterator is an interface that contains methods to retrieve the elements one by one from a collection object.It has three methods:

  1. boolean hasnext(): This method returns true if the the iterator has more elements.
  2. element next(): This method returns the next element in the iterator.
  3. void remove(): This method removes from the collection the last element returned by the iterator.





ListIterator Interface

ListIterator is an interface that contains methods to retrieve the elements from a collection object, both in forward and reverse direction.It has the following methods:

  1. boolean hasnext(): This method returns true if the the ListIterator has more elements when traversing the list in the forward direction.
  2. boolean hasPrevious(): This method returns true if the ListIterator has more elements when traversing the list in the reverse direction.
  3. element next(): This method returns the next element in the list.
  4. element previous(): This method returns the previous element in the list.
  5. void remove(): This method removes from the list the last element that was returned by the next() or previous() methods.