AS_
AS_

Reputation: 369

How does primitive array work with new for each loop in Java?

I understand that new for each loop works with Iterable and arrays, but I don't know what goes behind the scenes when working with arrays.

Can anyone help me understand this? Thanks in advance.

int[] number = new int[10];

for(int i: number) {

}

Upvotes: 25

Views: 22943

Answers (7)

KayV
KayV

Reputation: 13835

IntStream.range(1,4) can be used, if using java 8.

Upvotes: 0

DwB
DwB

Reputation: 38300

A bit late, but here it is.

The compiler knows if you are using the for-each loop statement for a collection or for an array.

If used for collection, the compiler translates the for-each loop to the equivalent for loop using an Iterator.

If used for an array, the compiler translates the for-each loop to the equivalent for loop using an index variable.

Here is a description at oracle.com

Upvotes: 11

AlexWien
AlexWien

Reputation: 28727

This is the equivalent to:

final int len = number.length;
for(int j = 0; j < len; j++) {
  int i = number[j];
}

Note that the forEach will not evaluate the .length in each loop. This might be also be eliminated by the JVM, but especially in case of collections, where some would use

for(int j = 0; j < collection.size(); j++) {

it makes a (small) difference to the faster

int len = collection.size()
for(int j = 0; j < len; j++) {

Upvotes: 1

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

this is equivalent to:

for(int x = 0; x < number.length; x++) {
  int i = number[x];
}

Upvotes: 2

Woot4Moo
Woot4Moo

Reputation: 24316

The for each over arrays is essentially "sugar" over this construct:

for(int i = 0;i<number.length;i++)
{  
}

I would imagine this was provided as a construct of the language so that people could use the enhanced for loop over a structure that was iterated over in the old way.

Upvotes: 0

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

The loop is equivalent to:

for(int j = 0; j < number.length; j++) {
  int i = number[j];
  ...
}

where j is an internally generated reference that does not conflict with normal user identifiers.

Upvotes: 16

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78579

In your code, you allocate an array of 10 integers in the memory and obtain a reference to it. In the for-loop you simply iterate over every item in the array, which initially will be 0 for all the items. The value of every item will be stored in the variable i declared in your for-loop as you iterate the array elements.

Upvotes: 3

Related Questions