Xonatron
Xonatron

Reputation: 16052

Do Java Iterators or Enhanced Loops guarantee results in order of creation?

Do Java Iterators or Enhanced Loops guarantee results in order of insertion? Please if the answer requires it, expand out an elaborate how Java handles ordering.

Examples of actual data structures in question:

1. Vector<String[]>
2. Iterator<String[]>

But my question was curious about all various data structures.

The problem in question concerns Oracle SQL database results. I run an ordered query and I wish to access the data in this exact order.

Upvotes: 3

Views: 2345

Answers (4)

Konstantin Solomatov
Konstantin Solomatov

Reputation: 10342

Java doesn't provide any guarantees for these however, in certain cases, items will be iterated in a particular order:

  • Lists and arrays will iterate over elements in order
  • TreeSet in sort order
  • LinkedHashSet in creation order

It all depends on what you're iterating over, and the particular implementation.

Upvotes: 8

CodeBlue
CodeBlue

Reputation: 15389

I think you mean "order of insertion" and not "creation". If that is so, the answer is yes for ordered collections like ArrayList for example.

Upvotes: 2

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7312

The enhanced loop is just interpreted like using an iterator by Java runtime. The total answer is no. For example when using SortedSets, or HashSets and ... the order of retrieving items is not the same as order of adding items to the Collection.

Lists are collections which shall reserve the order of items putting in them.

Upvotes: 2

MByD
MByD

Reputation: 137382

Yes and no.

It depends on the type of the collection. For example - ArrayList will be iterated in the order of addition, but set will not.

Upvotes: 2

Related Questions