問題描述
給定以下代碼片段:
int[] arr = {1, 2, 3};
for (int i : arr)
System.out.println(i);
我有以下問題:
- 上述 for-each 循環是如何工作的?
- 如何在 Java 中獲取數組的迭代器?
- 是否將數組轉換為列表以獲取迭代器?
推薦答案
如果你想要一個數組上的 Iterator
,你可以使用其中的一個直接實現,而不是將數組包裝在一個列表
.例如:
If you want an Iterator
over an array, you could use one of the direct implementations out there instead of wrapping the array in a List
. For example:
Apache Commons Collections ArrayIterator
或者,這個,如果你想使用泛型:
Or, this one, if you'd like to use generics:
com.Ostermiller.util.ArrayIterator
請注意,如果您想在原始類型上使用 Iterator
,則不能,因為原始類型不能是泛型參數.例如,如果你想要一個 Iterator<int>
,你必須使用 Iterator
int[]
.
Note that if you want to have an Iterator
over primitive types, you can't, because a primitive type can't be a generic parameter. E.g., if you want an Iterator<int>
, you have to use an Iterator<Integer>
instead, which will result in a lot of autoboxing and -unboxing if that's backed by an int[]
.
這篇關于增強的 for 語句如何用于數組,以及如何獲取數組的迭代器?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!