java 获取知道索引的 Collection 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13691643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:38:20  来源:igfitidea点击:

get element of Collection knowing the index?

javacollections

提问by Leon Kingston

Possible Duplicate:
best way to get value from Collection by index

可能的重复:
通过索引从集合中获取价值的最佳方式

Say I have a Collection. And I need to get the element at index 2.

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

How would I do this if there's no get method and iterator doesn't track indexes?

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

回答by Tomasz Nurkiewicz

First and foremost try to exploit the actual implementation. If it's a Listyou can downcast and use better API:

首先,最重要的是尝试利用实际实现。如果是这样,List您可以向下转型并使用更好的 API:

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

But the "pure" solution is to create an Iteratorand call next()two times. That's the only general interface you have:

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

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

This can be easily generalized to k-th element. But don't bother, there is already a method for that: Iterators.html#get(Iterator, int)in Guava:

这可以很容易地推广到第 k 个元素。但是别担心,已经有一个方法:Iterators.html#get(Iterator, int)在番石榴中:

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

...or with Iterables.html#get(Iterable, int):

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

Iterables.get(collection, 1);

If you need to do this many, many times, it might be cheaper to create a copy of the collection in ArrayList:

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

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