Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Given the following code snippet:

int[] arr = {1, 2, 3}; for (int i : arr)     System.out.println(i); 

I have the following questions:

  1. How does the above for-each loop work?
  2. How do I get an iterator for an array in Java?
  3. Is the array converted to a list to get the iterator?
like image 708
Emil Avatar asked Oct 12 '10 08:10

Emil


People also ask

Does enhanced loop use iterator?

Even though enhanced for loop internally uses an Iterator, it doesn't expose the reference to the outside world.

Can we use enhanced for loop for array?

There is a special kind of loop that can be used with arrays that is called an enhanced for loop or a for each loop. This loop is much easier to write because it does not involve an index variable or the use of the [].

What is the difference between iterator and enhanced for?

The difference is largely syntactic sugar except that an Iterator can remove items from the Collection it is iterating. Technically, enhanced for loops allow you to loop over anything that's Iterable, which at a minimum includes both Collections and arrays. Don't worry about performance differences.

How does an enhanced for loop work?

Enhanced for loop(for-each loop) This for-loop was introduced in java version 1.5 and it is also a control flow statement that iterates a part of the program multiple times. This for-loop provides another way for traversing the array or collections and hence it is mainly used for traversing array or collections.


1 Answers

If you want an Iterator over an array, you could use one of the direct implementations out there instead of wrapping the array in a List. For example:

Apache Commons Collections ArrayIterator

Or, this one, if you'd like to use generics:

com.Ostermiller.util.ArrayIterator

Note that if you want to have an Iterator over primitive types, you can't, because a primitive type can't be a generic parameter. E.g., if you want an Iterator<int>, you have to use an Iterator<Integer> instead, which will result in a lot of autoboxing and -unboxing if that's backed by an int[].

like image 166
uckelman Avatar answered Sep 23 '22 00:09

uckelman