gpt4 book ai didi

java从Set中检索对象

转载 作者:行者123 更新时间:2023-12-01 06:41:01 27 4
gpt4 key购买 nike

在 Java 5 中,如果我有一个 Set,并且我将两个对象添加到 Set 中。当我检索对象时,它会按照我添加的顺序返回给我吗?我无法找到这个问题的答案。这取决于我使用的 Set 实现吗?

最佳答案

是的,这取决于您使用的实现。例如,LinkedHashSet将保留插入顺序:

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

...但是HashSet不会:

It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

关于java从Set中检索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9216900/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com