Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two java.util.Iterators to the same collection: do they have to return elements in the same order?

This is more of a theoretical question. If I have an arbitrary collection c that isn't ordered and I obtain two java.util.Iterators by calling c.iterator() twice, do both iterators have to return c's elements in the same order?

I mean, in practice they probably always will, but are they forced to do so by contract?

Thanks, Jan

like image 226
Jan Van den bosch Avatar asked Dec 20 '22 21:12

Jan Van den bosch


2 Answers

No they are not.

"There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of some class that provides a guarantee)."

See the Collection#iterator api contract.

That includes from one iterator to the next (as it doesn't say anything about requiring that).

Also consider that something could have changed in the underlying collection between getting those two iterators! Something added or removed.

like image 174
Mattias Isegran Bergander Avatar answered Mar 02 '23 00:03

Mattias Isegran Bergander


Implementation of Iterators are provided by the specific Collection class. Iterator for List will give the ordered element while Set will not

like image 36
ejb_guy Avatar answered Mar 02 '23 01:03

ejb_guy