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

后端 未结 13 773
走了就别回头了
走了就别回头了 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: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());
    }
    }
    

提交回复
热议问题