Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I sort a List what happens to its iterators?

Let's say I have a List object and an iterator for that list.

Now I sort the list with java.util.Collections.sort()

  • What happens to the iterator?
  • Is its behavior still defined and can it still be used?
  • If not, can I prevent destroying the iterators for the list?

I know, this problem could be circumvented by changing the program design, cloning the list for example, but I specificly want to know the "official" behavior of Java.

like image 480
Daniel Rikowski Avatar asked Nov 18 '08 15:11

Daniel Rikowski


People also ask

Are iterators sorted?

They are collections that are already sorted. Yes, but they don't allow duplicates so they're not really substitutes for a List .

Does iterator maintain order?

The order in which the elements contained in a Java Iterator are traversed depends on the object that supplies the Iterator . For instance, an iterator obtained from a List will iterate through the elements of that List in the same order the elements are stored internally in the List .

What does list iterator do?

ListIterator is one of the four java cursors. It is a java iterator that is used to traverse all types of lists including ArrayList, Vector, LinkedList, Stack, etc. It is available since Java 1.2. It extends the iterator interface.

Can iterators be reused?

iterators are not reusable; you need to get a fresh Iterator from the Iterable collection each time you want to iterate over the elements.


2 Answers

Iterators are generally invalid after any modification to their underlying collections, except via the iterator itself. (For instance, ListIterator allows for insertion and removal.)

I'd certainly expect any iterators to become invalidated after a sort though - and if they weren't, I'd have no idea what order to expect.

like image 84
Jon Skeet Avatar answered Oct 13 '22 22:10

Jon Skeet


Most of the collections in java.util are "fail-fast" and may throw a ConcurrentModificationException if the underlying collection is changed. It should be pointed out that this is intended for debugging and so is not guaranteed. According to the javadocs, this is true of all decedents of AbstractList, but this is not true of CopyOnWriteArrayList, which is intended for multi-threaded use.

like image 26
sblundy Avatar answered Oct 13 '22 22:10

sblundy