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

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

    You can't directly get an iterator for an array.

    But you can use a List, backed by your array, and get an ierator on this list. For that, your array must be an Integer array (instead of an int array):

    Integer[] arr={1,2,3};
    List arrAsList = Arrays.asList(arr);
    Iterator iter = arrAsList.iterator();
    

    Note: it is only theory. You can get an iterator like this, but I discourage you to do so. Performances are not good compared to a direct iteration on the array with the "extended for syntax".

    Note 2: a list construct with this method doesn't support all methods (since the list is backed by the array which have a fixed size). For example, "remove" method of your iterator will result in an exception.

提交回复
热议问题