通过索引从 Collection 中获取价值的最佳方法 [英] Best way to get value from Collection by index
本文介绍了通过索引从 Collection 中获取价值的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通过索引从 java.util.Collection
获取价值的最佳方法是什么?
What is the best way to get value from java.util.Collection
by index?
推荐答案
你不应该.Collection
避免专门讨论索引,因为它可能对特定集合没有意义.例如,List
暗示某种形式的排序,但 Set
不暗示.
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.
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]);
给我:
elem = World
elem = Hello
myCollection.toArray()[0] = World
虽然:
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]);
给我:
elem = Hello
elem = World
myCollection.toArray()[0] = Hello
你为什么要这样做?你不能只是迭代集合吗?
Why do you want to do this? Could you not just iterate over the collection?
这篇关于通过索引从 Collection 中获取价值的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文