这更像是一个理论问题。如果我有一个未排序的任意集合 c
并且我通过调用 c.iterator()
获得了两个 java.util.Iterator
两次,两个迭代器是否必须以相同的顺序返回 c
的元素?
我的意思是,在实践中他们可能总是会这样做,但他们是根据契约(Contract)被迫这样做的吗?
谢谢, 简
最佳答案
不,他们不是。
"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)."
参见 Collection#iterator api contract .
这包括从一个迭代器到下一个迭代器(因为它没有说明任何要求)。
还要考虑在获取这两个迭代器之间底层集合中可能发生了一些变化!添加或删除的内容。
关于java - 同一个集合 : do they have to return elements in the same order? 的两个 java.util.Iterators,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10734953/