gpt4 book ai didi

java - 如何在 HashSet 中的特定索引/位置添加元素?

转载 作者:行者123 更新时间:2023-12-03 00:57:21 26 4
gpt4 key购买 nike

我有一些 String 元素的 HashSet 集合,如何在特定位置添加新元素?我查看了文档,但没有找到任何可以做到这一点的方法。

最佳答案

标准的一个方面 HashSet<T> 是它无序。所以你不能在特定索引处插入元素。或者如 documentation 中指定的那样:

This class implements the Set interface, backed by a hash table (actually a HashMap instance). 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.

当您进行插入、删除等操作时,HashSet<T> 可能会出现。将进行重新哈希。结果是 for(...) 中元素的顺序循环可以完全改变

存在 Hashset<T>扩展 LinkedHashSet<T> 它维护元素插入的顺序。

一个 TreeSet<T> 另一方面,使用树,并根据顺序关系对元素进行排序(小于另一个对象的对象在该元素之前发出)。

如果您可以在随机索引处插入一个元素,那会很奇怪,因为这会导致至少某些具有特定索引的操作需要 O(n) 时间。通常使用 HashSet<T>O(1)(平均时间)内执行插入、删除等操作。

关于java - 如何在 HashSet 中的特定索引/位置添加元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749052/

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