Maurdekye
Maurdekye

Reputation: 3697

Will getting the first item from the iterator of a set return a random value?

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

Answers (2)

orlandocr
orlandocr

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:

  • TreeSet: sorts elements based on their value (natural order)
  • ConcurrentSkipListSet: sorts elements based on their value (natural order)
  • LinkedHashSet: sorts elements based on the order they were inserted in the set (insertion order)

The first two implement the SortedSet interface.

Upvotes: 3

Rahul
Rahul

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

Related Questions