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

后端 未结 13 657
走了就别回头了
走了就别回头了 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<Integer> arrAsList = Arrays.asList(arr);
    Iterator<Integer> 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.

    0 讨论(0)
  • 2020-11-27 05:41

    Strictly speaking, you can't get an iterator of the primitive array, because Iterator.next() can only return an Object. But through the magic of autoboxing, you can get the iterator using the Arrays.asList() method.

    Iterator<Integer> it = Arrays.asList(arr).iterator();
    

    The above answer is wrong, you can't use Arrays.asList() on a primitive array, it would return a List<int[]>. Use Guava's Ints.asList() instead.

    0 讨论(0)
  • 2020-11-27 05:48

    In Java 8:

    Arrays.stream(arr).iterator();
    
    0 讨论(0)
  • 2020-11-27 05:48

    I like the answer from 30thh using Iterators from Guava. However, from some frameworks I get null instead of an empty array, and Iterators.forArray(array) does not handle that well. So I came up with this helper method, which you can call with Iterator<String> it = emptyIfNull(array);

    public static <F> UnmodifiableIterator<F> emptyIfNull(F[] array) {
        if (array != null) {
            return Iterators.forArray(array);
        }
        return new UnmodifiableIterator<F>() {
            public boolean hasNext() {
                return false;
            }
    
            public F next() {
                return null;
            }
        };
    }
    
    0 讨论(0)
  • 2020-11-27 05:52

    I'm a recent student but I BELIEVE the original example with int[] is iterating over the primitives array, but not by using an Iterator object. It merely has the same (similar) syntax with different contents,

    for (primitive_type : array) { }
    
    for (object_type : iterableObject) { }
    

    Arrays.asList() APPARENTLY just applies List methods to an object array that it's given - but for any other kind of object, including a primitive array, iterator().next() APPARENTLY just hands you the reference to the original object, treating it as a list with one element. Can we see source code for this? Wouldn't you prefer an exception? Never mind. I guess (that's GUESS) that it's like (or it IS) a singleton Collection. So here asList() is irrelevant to the case with a primitives array, but confusing. I don't KNOW I'm right, but I wrote a program that says that I am.

    Thus this example (where basically asList() doesn't do what you thought it would, and therefore is not something that you'd actually use this way) - I hope the code works better than my marking-as-code, and, hey, look at that last line:

    // Java(TM) SE Runtime Environment (build 1.6.0_19-b04)
    
    import java.util.*;
    
    public class Page0434Ex00Ver07 {
    public static void main(String[] args) {
        int[] ii = new int[4];
        ii[0] = 2;
        ii[1] = 3;
        ii[2] = 5;
        ii[3] = 7;
    
        Arrays.asList(ii);
    
        Iterator ai = Arrays.asList(ii).iterator();
    
        int[] i2 = (int[]) ai.next();
    
        for (int i : i2) {
            System.out.println(i);
        }
    
        System.out.println(Arrays.asList(12345678).iterator().next());
    }
    }
    
    0 讨论(0)
  • 2020-11-27 05:58

    Arrays.asList(arr).iterator();

    Or write your own, implementing ListIterator interface..

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