Java 通过索引从 Collection 中获取价值的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1047957/
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
Best way to get value from Collection by index
提问by keo
What is the best way to get value from java.util.Collection
by index?
java.util.Collection
通过索引获取价值的最佳方法是什么?
回答by Bhushan Bhangale
Convert the collection into an array by using function
使用函数将集合转换为数组
Object[] toArray(Object[] a)
回答by Matthew Flaschen
In general, there is no good way, as Collection
s are not guaranteed to have fixed indices. Yes, you can iterate through them, which is how toArray (and other functions) work. But the iteration order isn't necessarily fixed, and if you're trying to index into a general Collection, you're probably doing something wrong. It would make more sense to index into a List.
一般来说,没有好的方法,因为Collection
s 不能保证有固定的索引。是的,您可以遍历它们,这就是 toArray(和其他函数)的工作原理。但是迭代顺序不一定是固定的,如果你试图索引到一个通用的集合中,你可能做错了什么。索引到List会更有意义。
回答by butterchicken
You shouldn't. a Collection
avoids talking about indexes specifically because it might not make sense for the specific collection. For example, a List
implies some form of ordering, but a Set
does not.
你不应该。aCollection
避免专门讨论索引,因为它可能对特定集合没有意义。例如,aList
暗示某种形式的排序,但 aSet
不暗示。
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]);
gives me:
给我:
elem = World
elem = Hello
myCollection.toArray()[0] = World
whilst:
同时:
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]);
gives me:
给我:
elem = Hello
elem = World
myCollection.toArray()[0] = Hello
Why do you want to do this? Could you not just iterate over the collection?
你为什么要这样做?你不能只是迭代集合吗?
回答by Aaron Digulla
You must either wrap your collection in a list (new ArrayList(c)
) or use c.toArray()
since Collections have no notion of "index" or "order".
您必须将集合包装在列表 ( new ArrayList(c)
) 中或使用,c.toArray()
因为集合没有“索引”或“顺序”的概念。
回答by akarnokd
I agree with Matthew Flaschen's answer and just wanted to show examples of the options for the case you cannot switch to List (because a library returns you a Collection):
我同意Matthew Flaschen的回答,只是想展示您无法切换到 List 的情况下的选项示例(因为图书馆会返回给您一个集合):
List list = new ArrayList(theCollection);
list.get(5);
Or
或者
Object[] list2 = theCollection.toArray();
doSomethingWith(list[2]);
If you know what generics is I can provide samples for that too.
如果您知道什么是泛型,我也可以为此提供示例。
Edit:It's another question what the intent and semantics of the original collection is.
编辑:这是另一个问题,原始集合的意图和语义是什么。
回答by dfa
you definitively want a List:
你绝对想要一个List:
The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based.
List 接口提供了四种对列表元素进行位置(索引)访问的方法。列表(如 Java 数组)是从零开始的。
Also
还
Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a > list is typically preferable to indexing through it if the caller does not know the implementation.
请注意,对于某些实现(例如 LinkedList 类),这些操作的执行时间可能与索引值成正比。因此,如果调用者不知道实现,则迭代 > 列表中的元素通常比通过它进行索引更可取。
If you need the index in order to modify your collection you should note that List provides a special ListIteratorthat allow you to get the index:
如果你需要索引来修改你的集合,你应该注意 List 提供了一个特殊的ListIterator允许你获取索引:
List<String> names = Arrays.asList("Davide", "Francesco", "Angelocola");
ListIterator<String> i = names.listIterator();
while (i.hasNext()) {
System.out.format("[%d] %s\n", i.nextIndex(), i.next());
}
回答by JodaStephen
I agree that this is generally a bad idea. However, Commons Collectionshad a nice routine for getting the value by index if you really need to:
我同意这通常是一个坏主意。但是,如果您确实需要,Commons Collections有一个很好的例程可以通过索引获取值:
回答by LifesAway
It would be just as convenient to simply convert your collection into a list whenever it updates. But if you are initializing, this will suffice:
每当您的收藏更新时,只需将其转换为列表同样方便。但是,如果您正在初始化,这就足够了:
for(String i : collectionlist){
arraylist.add(i);
whateverIntID = arraylist.indexOf(i);
}
Be open-minded.
心胸开阔。
回答by apksatheesh
use for each loop...
用于每个循环...
ArrayList<Character> al = new ArrayList<>();
String input="hello";
for (int i = 0; i < input.length(); i++){
al.add(input.charAt(i));
}
for (Character ch : al) {
System.Out.println(ch);
}
回答by Soni Vashisht
You can get the value from collection using for-each loop or using iterator interface. For a Collection c for (<ElementType> elem: c)
System.out.println(elem);
or Using Iterator Interface
您可以使用 for-each 循环或使用迭代器接口从集合中获取值。对于集合 cfor (<ElementType> elem: c)
System.out.println(elem);
或使用迭代器接口
Iterator it = c.iterator();
while (it.hasNext())
System.out.println(it.next());