如何获取java.util.Set中项的索引 [英] How to get index of an item in java.util.Set
问题描述
我知道Set和List之间的区别(允许唯一与重复,不订购/订购等)。我正在寻找的是一个保持元素排序的集合(这很容易),但我还需要能够恢复插入元素的索引。因此,如果我插入四个元素,那么我希望能够知道插入其中一个元素的顺序。
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?
推荐答案
<$ c $中的一个小的静态自定义方法c> Util class会有所帮助:
A small static custom method in a Util
class would help:
public static int getIndex(Set<? extends Object> set, Object value) {
int result = 0;
for (Object entry:set) {
if (entry.equals(value)) return result;
result++;
}
return -1;
}
如果您需要/想要一个是的课程> 设置
并提供 getIndex()
方法,我强烈建议实现一个新的 Set
并使用装饰器模式:
If you need/want one class that is a Set
and offers a getIndex()
method, I strongly suggest to implement a new Set
and use the decorator pattern:
public class IndexAwareSet<T> implements Set {
private Set<T> set;
public IndexAwareSet(Set<T> set) {
this.set = set;
}
// ... implement all methods from Set and delegate to the internal Set
public int getIndex(T entry) {
int result = 0;
for (T entry:set) {
if (entry.equals(value)) return result;
result++;
}
return -1;
}
}
这篇关于如何获取java.util.Set中项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!