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

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

    public class ArrayIterator implements Iterator {
      private T array[];
      private int pos = 0;
    
      public ArrayIterator(T anArray[]) {
        array = anArray;
      }
    
      public boolean hasNext() {
        return pos < array.length;
      }
    
      public T next() throws NoSuchElementException {
        if (hasNext())
          return array[pos++];
        else
          throw new NoSuchElementException();
      }
    
      public void remove() {
        throw new UnsupportedOperationException();
      }
    }
    

提交回复
热议问题