Searching for "Iterator"

Q:

What’s the difference between Enumeration and Iterator interfaces ?

Answer

Enumeration is twice as fast as compared to an Iterator and uses very less memory. However, the Iterator is much safer compared to Enumeration, because other threads are not able to modify the collection object that is currently traversed by the iterator. Also, Iteratorsallow the caller to remove elements from the underlying collection, something which is not possible with Enumerations.

Report Error

View answer Workspace Report Error Discuss

Subject: Java

Q:

How do you traverse through a collection using its Iterator?

Answer

To use an iterator to traverse through the contents of a collection, follow these steps:


- Obtain an iterator to the start of the collection by calling the collections iterator() method.


- Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.


- Within the loop, obtain each element by calling next().

Report Error

View answer Workspace Report Error Discuss

Subject: Java