Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to know how to "reset" LinkedList iterator to its first element.

For example:

LinkedList<String> list;

Iterator iter=list.listIterator;

iter.next();

iter.next();

Over and over again and after many moves of the iterator I need to "reset" the position of iterator. `

I want to ask how I can "reset" my iterator to first element

I know that I can get list iterator of the first element in this way:

iter= list.listIterator(1);

Is this the best solution? or maybe I missed something in Oracle docs?

question from:https://stackoverflow.com/questions/13689288/java-reset-list-iterator-to-first-element-of-the-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
435 views
Welcome To Ask or Share your Answers For Others

1 Answer

Best would be not using LinkedList at all, usually it is slower in all disciplines, and less handy. (When mainly inserting/deleting to the front, especially for big arrays LinkedList is faster)

Use ArrayList, and iterate with

int len = list.size();
for (int i = 0; i < len; i++) {
  Element ele = list.get(i);
}

Reset is trivial, just loop again.
If you insist on using an iterator, then you have to use a new iterator:

iter = list.listIterator();

(I saw only once in my life an advantage of LinkedList: i could loop through whith a while loop and remove the first element)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...