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

╄→гoц情女王★ 提交于 2019-12-10 17:25:28

问题


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


回答1:


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.




回答2:


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




回答3:


Because most Data structures are not ordered by default so it is not certain that they will iterate in same order.

If you want same order you have to sort the collection first.



来源:https://stackoverflow.com/questions/10734953/two-java-util-iterators-to-the-same-collection-do-they-have-to-return-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!