How does the enhanced for statement work for arrays, and how to get an iterator for an array?

后端 未结 13 810
走了就别回头了
走了就别回头了 2020-11-27 04:59

Given the following code snippet:

int[] arr = {1, 2, 3};
for (int i : arr)
    System.out.println(i);

I have the following questions:

13条回答
  •  广开言路
    2020-11-27 05:34

    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

    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, you have to use an Iterator instead, which will result in a lot of autoboxing and -unboxing if that's backed by an int[].

提交回复
热议问题