java 没有重复的列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7961327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:13:14  来源:igfitidea点击:

List without duplicates?

javalistcollections

提问by LuxuryMode

I just read Is there a no-duplicate List implementation out there?answer about a List, NOT Set, implementation that doesn't allow duplicates. The accepted answer recommended the Collections15 SetUniqueList. Is there some equivalent -- in Guava perhaps? (I searched the docs and couldn't find) -- in other libs or is there some other currently popular solution?

我刚读到那里有没有重复的 List 实现吗?回答关于 a List, NOT Set,不允许重复的实现。接受的答案推荐了 Collections15 SetUniqueList。是否有一些等价物——也许在番石榴中?(我搜索了文档但找不到)--在其他库中还是有其他一些当前流行的解决方案?

回答by

I like to require the correct Java Semantic when I have a Collection that should not have any duplicates, and that is to use the Setinterface. That said, in many cases you want to preserve the insertion order like a Listwould for convenience, maintaining two parallel data structures seems wasteful and complicated to keep in sync. That is why I use something like this. InsertionOrderSet.javaThis is a special implementation of SortedSetthat uses a wrapper object to maintain and indexthat can be sorted on by a comparator, but hides that implementation detail from the external consumers so it just looks like a regular old type safe SortedSet.

当我有一个不应该有任何重复的集合时,我喜欢要求正确的 Java 语义,那就是使用Set接口。也就是说,在许多情况下,为了List方便起见,您希望保留插入顺序,而维护两个并行数据结构似乎既浪费又复杂,以保持同步。这就是为什么我使用这样的东西。InsertionOrderSet.java这是一个特殊的实现,SortedSet它使用一个包装对象来维护并且index可以通过比较器对其进行排序,但是对外部使用者隐藏了该实现细节,因此它看起来就像一个普通的旧类型安全SortedSet

回答by G_H

The stuff in the answer you linked seems quite adequate. I'd go with one of those solutions. Alternatively, you could simply extend class ArrayListand override some of the methods that do a check against a HashSetprior to calling super.methodfor that same method. Simply add the Set as an instance field, use it for checking dupes and add/remove whatever items get added to/removed from the list.

您链接的答案中的内容似乎足够了。我会选择其中一种解决方案。或者,您可以简单地扩展类ArrayList并覆盖一些HashSet在调用super.method相同方法之前对 a进行检查的方法。只需将 Set 添加为实例字段,使用它来检查重复项并添加/删除从列表中添加/删除的任何项目。