通过索引从Collection获取价值的最佳方式

keo*_*keo 42 java collections

java.util.Collection索引中获取价值的最佳方法是什么?

but*_*ken 54

你不应该.a Collection避免专门讨论索引,因为它可能对特定集合没有意义.例如,a List表示某种形式的排序,但a表示Set不排序.

Collection<String> myCollection = new HashSet<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);
Run Code Online (Sandbox Code Playgroud)

给我:

elem = World
elem = Hello
myCollection.toArray()[0] = World
Run Code Online (Sandbox Code Playgroud)

同时:

myCollection = new ArrayList<String>();
myCollection.add("Hello");
myCollection.add("World");

for (String elem : myCollection) {
    System.out.println("elem = " + elem);
}

System.out.println("myCollection.toArray()[0] = " + myCollection.toArray()[0]);
Run Code Online (Sandbox Code Playgroud)

给我:

elem = Hello
elem = World
myCollection.toArray()[0] = Hello
Run Code Online (Sandbox Code Playgroud)

你为什么要这样做?你能不能迭代收藏?


Mat*_*hen 18

一般来说,没有好办法,因为Collection不能保证有固定的指数.是的,您可以遍历它们,这是如何(和其他功能)工作的.但迭代顺序不一定是固定的,如果你试图索引到一般的集合,你可能做错了.索引到List更有意义.


aka*_*okd 17

我同意Matthew Flaschen的回答,并且只想展示无法切换到List的情况的选项示例(因为库会返回一个Collection):

List list = new ArrayList(theCollection);
list.get(5);
Run Code Online (Sandbox Code Playgroud)

要么

Object[] list2 = theCollection.toArray();
doSomethingWith(list[2]);
Run Code Online (Sandbox Code Playgroud)

如果您知道什么是仿制药,我也可以为此提供样品.

编辑:这是另一个问题,原始集合的意图和语义是什么.


Jod*_*hen 10

我同意这通常是一个坏主意.但是,如果您真的需要,Commons Collections有一个很好的例程来获取索引值:

CollectionUtils.get(集合,索引)


Aar*_*lla 5

您必须将集合包装在list(new ArrayList(c))中或使用,c.toArray()因为集合没有"index"或"order"的概念.


Bhu*_*ale 3

使用函数将集合转换为数组

Object[] toArray(Object[] a) 
Run Code Online (Sandbox Code Playgroud)