是否有一个保留插入顺序的 Set 也实现了 List? [英] Is there an insertion order preserving Set that also implements List?
问题描述
我正在尝试在 Java 中同时找到 java.util.List
和 java.util.Set
的实现.我希望这个类只允许唯一的元素(如 Set
)并保留它们的顺序(如 List
).它存在于 JDK 6 中吗?
I'm trying to find an implementation of java.util.List
and java.util.Set
at the same time in Java. I want this class to allow only unique elements (as Set
) and preserve their order (like List
). Does it exist in JDK 6?
List
很重要,这样我就可以插入到特定位置.
It's important to have List<T>#add(int, T)
so I can insert into a specific position.
推荐答案
TreeSet
按元素顺序排序;LinkedHashSet
保留插入顺序.希望其中之一是您所追求的.
TreeSet
is sorted by element order; LinkedHashSet
retains insertion order. Hopefully one of those is what you were after.
您已指定要能够在任意位置插入,我怀疑您必须自己编写 - 只需创建一个包含 HashSet
和一个 ArrayList
;添加项目时,先检查它是否在集合中,然后再添加到列表中.
You've specified that you want to be able to insert at an arbitrary location, I suspect you'll have to write your own - just create a class containing a HashSet<T>
and an ArrayList<T>
; when adding an item, check whether or not it's in the set before adding it to the list.
或者 Apache 的 commons-collections4 提供 ListOrderedSet
和 SetUniqueList
,它们的行为类似并且应该满足给定的要求.
Alternatively Apache's commons-collections4 offers ListOrderedSet
and SetUniqueList
, which behave similarly and should meet the given requirements.
这篇关于是否有一个保留插入顺序的 Set 也实现了 List?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!