java的怎么获取set里的元素,如何获取java.util.Set中项的索引

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 set = MySet();

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?

解决方案

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;

}

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 implements Set {

private Set set;

public IndexAwareSet(Set 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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值