英文:
looking for a special java collection
问题
有没有一种 Java 集合,只允许插入唯一的对象,并且带有一个 get (index i) 方法?
起初我考虑了 TreeSet,但是它没有 get 方法...
我想要能够做到以下操作:
// 将 object 替换为任何实现了正确功能的类
Collection<Object> collection = dunno<Object>();
Object o = new Object();
Object o2 = new Object();
collection.add(o);
collection.add(o);
collection.size(); // 应该得到 1
collection.get(0); // 应该返回 o
// 假设 o2 小于 o (如果集合不按我想要的方式排序,我可以随意更改)
collection.add(o2);
collection.get(0); // 应该返回 o2
基本上像 TreeSet 一样,但带有一个 get 方法,有人知道有类似的吗?
英文:
Is there a java collection that only allow unique object in and with a get (index i) method ?
i firstly think of a treeSet but there is no get methods in ...
what i want be able to :
// 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
so basicly like a treeSet but with a get methods does anyone know something like that ?
答案1
得分: 1
没有在标准库中找到这样的集合,我也不知道类似的在其他广泛使用的库(如Guava或Apache Commons)中是否有。
因此答案是:您将不得不为此实现自己的集合。一个直接的解决方案是使用集合和列表来提供所需的接口,这将可以工作,但显然会在一定程度上增加内存占用。
英文:
There is no such collection in the in the standard library, and I am also not aware of something like that in other widespread libraries like guava or apache commons.
Thus the answer is: you will have to implement your own collection for that. A straight forward solution would use a set and a list to provide the required interface, which will work but obviously increase the memory footprint to a certain degree.
答案2
得分: 0
覆盖自定义类中的equals
和hashcode
方法,在你的自定义类中使用ArrayList
,在添加元素之前可以使用list.contains
进行检查,以便去除重复元素。
英文:
override equals
and hashcode
in ur custom class
use Arraylist
and u can check list.contains
before adding to remove duplicate
答案3
得分: 0
LinkedHashSet 在保持插入顺序的同时也保持了插入的项的唯一性。
虽然它没有专门的 get(i) 方法,但你可以通过遍历集合来实现这样一个方法。
不过,你会在性能上付出一些代价。
英文:
The LinkedHashSet maintains the order of insertion while maintaining also the uniqueness of the items inserted.
Although it doesn’t have a dedicated get(i) method you can implement one by just iterating through the set.
You will pay for the performance of get() though.
答案4
得分: -1
你应该使用LinkedHashSet
。
这个集合只接受唯一的对象,并且会保持它们的顺序。
英文:
You should use the LinkedHashSet
.
This collection does only accept unique objects and keeps track of the order
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论