如何获取 java.util.Set 中项目的索引
我知道 Set 和 List 之间的区别(允许唯一与允许重复、不有序/有序等)。我正在寻找的是一个保持元素有序的集合(这很容易),但我还需要能够恢复插入元素的索引。因此,如果我插入四个元素,那么我希望能够知道其中一个元素的插入顺序。
MySet<String> set = MySet<String>();
set.add("one");
set.add("two");
set.add("three");
set.add("four");
int index = set.getIndex("two");
因此,在任何给定时刻,我都可以检查是否已添加字符串,并获取该字符串在集合中的索引。有这样的事情吗,还是需要我自己实现?
I know the differences between Set and List(unique vs. duplications allowed, not ordered/ordered, etc). What I'm looking for is a set that keeps the elements ordered(that's easy), but I also need to be able to recover the index in which an element was inserted. So if I insert four elements, then I want to be able to know the order in which one of them was inserted.
MySet<String> set = MySet<String>();
set.add("one");
set.add("two");
set.add("three");
set.add("four");
int index = set.getIndex("two");
So at any given moment I can check if a String was already added, and get the index of the string in the set. Is there anything like this, or I need to implement it myself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
创建 Set 后,只需将其转换为 List 并从 List 中按索引获取:
After creating Set just convert it to List and get by index from List:
Util
类中的一个小型静态自定义方法会有所帮助:如果您需要/想要一个是
Set
并提供的类getIndex()
方法,我强烈建议实现一个新的Set
并使用装饰器模式:A small static custom method in a
Util
class would help:If you need/want one class that is a
Set
and offers agetIndex()
method, I strongly suggest to implement a newSet
and use the decorator pattern:您可以扩展
LinkedHashSet
添加您想要的getIndex()
方法。实施和测试需要 15 分钟。只需使用迭代器和计数器遍历集合,检查对象是否相等。如果找到,则返回计数器。you can extend
LinkedHashSet
adding your desiredgetIndex()
method. It's 15 minutes to implement and test it. Just go through the set using iterator and counter, check the object for equality. If found, return the counter.一种解决方案(虽然不是很漂亮)是使用 Apache 通用列表/集突变,
它是一个没有重复项的列表
https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2 /index.html?org/apache/commons/collections/list/SetUniqueList.html
One solution (though not very pretty) is to use Apache common List/Set mutation
it is a list without duplicates
https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/index.html?org/apache/commons/collections/list/SetUniqueList.html
如何将字符串添加到哈希表中,其中值是索引:
How about add the strings to a hashtable where the value is an index:
您可以将设置的数据发送到新列表
you can send your set data to a new list