【发布时间】:2020-08-19 07:04:04
【问题描述】:
是否有一个 java 集合只允许在 get (index i) 方法中使用唯一对象?
我首先想到的是一个 treeSet,但在 ...
中没有 get 方法
我想要什么:
// replace object with any class that implement the right things to make it work
Collection<Object> collection = dunno<Object>();
Object o = new Object()
Object o2 = new Object()
collection.add(o)
collection.add(o)
collection.size() // should get 1
collection.get(0) // should return o
// let's suppose that o2 is lower than o (if the collection doesn't sort the way i want i can change it anyway)
collection.add(o2)
collection.get(0) // should return o2
基本上就像一个treeSet,但是有一个get方法,有人知道类似的东西吗?
【问题讨论】:
-
如果需要,您可以在添加到
List之前始终使用contains -
是的,使用包含和添加到列表的速度与添加到 treeSet 一样快,尤其是对于一些大型集合,这可能是一个好主意?我可以轻松地处理一千多个元素...
-
这能回答你的问题吗? Any implementation of Ordered Set in Java?
-
@SomeDude 链接到的问题中的答案建议 LinkedHashSet
标签: java