Java List Iterator Example
In Java Collection framework every classes provides the iterator() method, that returns the objects of iterator which used to start the collection. By using this iterator objects you can access each element in a collection.
An example given below
At fist make an object and add some data into it as
// Declaring ArrayList object of type String ListmyList = new ArrayList ();
Then add some elements of type String into it as
// Adding elements to the list myList.add("Rohan"); myList.add("Johan"); myList.add("Sams"); myList.add("Ram"); myList.add("Ramesh"); myList.add("Andrew");
Now call the iterator() method of list and store the result into the Iterator object as
/********** Iteration **********/ Iterator iterator = myList.iterator();
This method returns the iterator object which is used to start the collection
To access all the elements stored in a list apply the loop as
while (iterator.hasNext()) { System.out.println(iterator.next()); }
Please note the method used above of iterator objects, hasNext() and next()
The hasNext() method returns true if any element present in the loop and the next() method returns the next element from the collection
There are more methods present in the iterator interface, to read them please visit the Sun or Oractle site
When you run this application it will display message as shown below:
Rohan Johan Sams Ram Ramesh Andrew |