Hi, Can I use the same Iterator object to print the elements in the List twice? Is there any way to do like that.
I know that once we traverse the collection using the Iterator object, IS IT POSSIBLE TO TRAVERSE THE SAME COLLECTION OBJECT AGAIN USING SAME Iterator object to print the elements.. ************************************************************************** // Here my doubt is: Is there a way to use the same Iterator // to traverse the same collection twice by giving the same output. ***************************************************************************
My Code is as follows: ___________________________________________________________________________ package com.kris.tigerv.ch2;
The second set starting with 'four' is a sorted list.
Chandra Bhatt
Ranch Hand
Joined: Feb 28, 2007
Posts: 1707
posted
0
Can I use the same Iterator object to print the elements in the List twice?
I would say, "NO". "Iterator object is for one time use!"
M Krishnan says, Yes, you can..
In your example, if you see carefully, you are getting two iterator objects to traverse from the list. As said, Iterator object is for one time use. We can use the phrase "USE AND THROW" for the iterator.
Each time you need to traverse from the List you create a new iterator, means calling list.iterator(); gives you new iterator object.
However, you could play with ListIterator which is a bidirectional Iterator. So, when you get to the end of the list you reset the ListIterator by going backwards until you get to the point where hasPrevious() returns false. Then you can go forwards again. Rather inefficient methinks, but it "solves" the stated problem.
From your response I understood that, Iterator object can be used only once for traversing the Collection. If i need to traverse the same collection 2nd time then i need to create one more Iterator object.