我有一些 String 元素的 HashSet 集合,如何在特定位置添加新元素?我查看了文档,但没有找到任何可以做到这一点的方法。
最佳答案
标准的一个方面 HashSet<T>
是它无序。所以你不能在特定索引处插入元素。或者如 documentation 中指定的那样:
This class implements the
Set
interface, backed by a hash table (actually aHashMap
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 thenull
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/