简体   繁体   English

两个java.util.Iterators到同一个集合:他们必须以相同的顺序返回元素吗?

[英]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.Iterator s by calling c.iterator() twice, do both iterators have to return c 's elements in the same order? 如果我有一个没有排序的任意集合c并且我通过调用c.iterator()两次获得两个java.util.Iterator ,那么两个迭代器都必须以相同的顺序返回c的元素吗?

I mean, in practice they probably always will, but are they forced to do so by contract? 我的意思是,在实践中他们可能永远都会,但他们是否被迫通过合同这样做?

Thanks, Jan 谢谢,Jan

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 . 请参阅Collection#iterator api合约

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. 添加或删除的东西。

Implementation of Iterators are provided by the specific Collection class. 迭代器的实现由特定的Collection类提供。 Iterator for List will give the ordered element while Set will not List的Iterator将给出有序元素,而Set则不给出

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. 如果您想要相同的订单,则必须先对集合进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM