我目前正在寻找 Set 的 Java 实现,它保留原始插入顺序并提供按索引的访问。另外,我想要一个批量appendAll()方法,它接受另一个集合并将其附加到末尾(重复项除外,因为这是一个集合)。
LinkedHashSet在某种程度上朝着正确的方向发展,但它缺少索引访问和批量附加。
我可以自己写这个,但为什么要重新发明轮子?
最佳答案
怎么样ListOrderedSet在 Apache Commons 中?
Decorates another Set to ensure that the order of addition is retained and used by the iterator.
If an object is added to the set for a second time, it will remain in the original position in the iteration. The order can be observed from the set via the iterator or toArray methods.
The ListOrderedSet also has various useful direct methods. These include many from List, such as get(int), remove(int) and indexOf(int). An unmodifiable List view of the set can be obtained via asList().
它实现了 java.util.Set,但由于 .get(index)
不是 Set 定义的方法,因此您需要确保将其作为 ListOrderedSet 而不是 Set 传递。
关于java - 设置保持插入顺序并提供索引访问的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19183756/