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

后端 未结 13 808
走了就别回头了
走了就别回头了 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: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 it = emptyIfNull(array);

    public static  UnmodifiableIterator emptyIfNull(F[] array) {
        if (array != null) {
            return Iterators.forArray(array);
        }
        return new UnmodifiableIterator() {
            public boolean hasNext() {
                return false;
            }
    
            public F next() {
                return null;
            }
        };
    }
    

提交回复
热议问题