【问题标题】:get element of Collection knowing the index? [duplicate]获取知道索引的集合元素? [复制]
【发布时间】:2012-11-21 09:56:27
【问题描述】:

可能重复:
best way to get value from Collection by index

假设我有一个Collection。我需要获取索引 2 处的元素。

如果没有 get 方法并且迭代器不跟踪索引,我该怎么做?

【问题讨论】:

  • 集合只是一个接口,你用的是哪个集合?
  • 除非你有一个有序的 List 或一个有序的 Set,否则在索引 2 处获取一个元素可能是没有意义的。
  • 如果您想保持订单,最好使用列表。

标签: java collections


【解决方案1】:

首先尝试利用实际实现。如果是List,您可以选择使用更好的 API:

if(collection instanceof List) {
  ((List<Foo>)collection).get(1);
}

但“纯”解决方案是创建一个Iterator 并调用next() 两次。这是您拥有的唯一通用界面:

Iterator<Foo> fooIter = collection.iterator();
fooIter.next();
Foo second = fooIter.next();

这可以很容易地推广到第 k 个元素。不过不用麻烦,已经有一种方法可以做到这一点:Iterators.html#get(Iterator, int) in Guava:

Iterators.get(collection.iterator(), 1);

...或Iterables.html#get(Iterable, int):

Iterables.get(collection, 1);

如果您需要多次执行此操作,在ArrayList 中创建集合的副本可能会更便宜:

ArrayList<Foo> copy = new ArrayList<Foo>(collection);
copy.get(1); //second

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-16
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    相关资源
    最近更新 更多