知道索引的集合元素?

Leo*_*ton 3 java collections

可能重复:
从索引获取Collection值的最佳方法

说我有一个Collection.我需要在索引2处获取元素.

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

Tom*_*icz 12

首先尝试利用实际的实现.如果它是a,List你可以向下转换并使用更好的API:

if(collection instanceof List) {
  ((List<Foo>)collection).get(1);
}
Run Code Online (Sandbox Code Playgroud)

但" 纯粹 "的解决方案是创建Iterator并调用next()两次.这是你拥有的唯一通用界面:

Iterator<Foo> fooIter = collection.iterator();
fooIter.next();
Foo second = fooIter.next();
Run Code Online (Sandbox Code Playgroud)

这可以很容易地推广到第k个元素.但是不要打扰,已经有了一种方法:Iterators.html#get(Iterator, int)在番石榴:

Iterators.get(collection.iterator(), 1);
Run Code Online (Sandbox Code Playgroud)

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

Iterables.get(collection, 1);
Run Code Online (Sandbox Code Playgroud)

如果您需要多次执行此操作,则在以下位置创建集合副本可能更便宜ArrayList:

ArrayList<Foo> copy = new ArrayList<Foo>(collection);
copy.get(1); //second
Run Code Online (Sandbox Code Playgroud)