Accessing a Collection Via an Iterator Java Help

Accessing a Collection Via an Iterator

Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. By far, the easiest way to do this is to employ an iterator, an object that implements either the Iterator or the Listiterator interface. Iterator enables you to cycle through il collection, obtaining or removing elements. List Iterator extends Iterator to allow bidirectional traversal of a list, and the
modification of elements. The Iterator interface declares the methods . The methods declared

Using an Iterator

Before You can access a collection through an item tor, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you ‘can access each element in the collection, one element at a time. In general, to use an iterator to cycle through the contents of a collection, follow these steps:

1. Obtain an Iterator to the start of the collection by calling the collection’s iterator ) method .
.2. Set up a loop that makes a call to hasNext ). Have the loop iterate as long as Next() returns true. .
3. Within the loop, obtain each element by calling ncxt( ).

For collections that implement List, you can also obtain an iterator by calling ListIterator. As explained, a list iterator gives you the ability to access the collection in either the forward or backward direction and lets you modify an clement. Otherwise,’ Listiterator is used just like Iterator. ‘ Here is an example that implements these steps, demonstrating both Iterator and ListIterator. It uses an Arraylist object, but the general principles apply to tiny type of . collection. Of course, ListIterator is available only to those collections that implement the List interface.

The output is shown ~ere: Original contents of al: CAE B 0 F Modified contents of al: C+ A+ E+ B+ D+ F+ Modified list backwards: P+ D+ B+ E+ A+ C+

  • Feel free to send us an inquiry, we will reply back in hours.


Posted on September 17, 2014 in java util Part 1 The Collections Framework

Share the Story

About the Author

Back to Top