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

后端 未结 13 659
走了就别回头了
走了就别回头了 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:59

    No, there is no conversion. The JVM just iterates over the array using an index in the background.

    Quote from Effective Java 2nd Ed., Item 46:

    Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once.

    So you can't get an Iterator for an array (unless of course by converting it to a List first).

    0 讨论(0)
提交回复
热议问题