Reputation: 3697
I'm using Set#iterator().next();
all by itself, and I'm wondering if:
A) Will that cause memory leaks, or at least any kind of avoidable overhead,
and
B) Whether or not item it returns will be a random item, and if I use this method multiple times, it'll give a different item every time?
Upvotes: 1
Views: 570
Reputation: 323
Iterator<E> iterator()
Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).
http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#iterator()
If you need to get the elements in the same order every time you iterate through the Set, try one of these specific implementations that guarantee order:
The first two implement the SortedSet interface.
Upvotes: 3
Reputation: 45080
From the docs of Iterator#next()
Returns the next element in the iteration.
Which means that it'll return the items in the order they are stored in the Set
. And regarding the different item, Yes, it'll return next(different) item always(till there are more items remaining in the Set) and will terminate(by throwing the NoSuchElementException
) once it has exhausted all of them.
Upvotes: 1