Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a variable length array

Tags:

How do I iterate over a Java array of variable length.

I guess I would setup a while loop, but how would I detect that I have reached the end of the array.

I guess I want something like this [just need to figure out how to represent myArray.notEndofArray()]

index = 0; while(myArray.notEndofArray()){   system.out.println(myArray(index));   index++; } 
like image 376
Ankur Avatar asked Feb 25 '10 03:02

Ankur


2 Answers

for(int i = 0; i < array.length; i++) {     System.out.println(array[i]); } 

or

for(String value : array) {     System.out.println(value); } 

The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.

Just for completeness you can do the while loop this way:

int index = 0;  while(index < myArray.length) {   final String value;    value = myArray[index];   System.out.println(value);   index++; } 

But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).

like image 143
TofuBeer Avatar answered Sep 24 '22 11:09

TofuBeer


Arrays have an implicit member variable holding the length:

for(int i=0; i<myArray.length; i++) {     System.out.println(myArray[i]); } 

Alternatively if using >=java5, use a for each loop:

for(Object o : myArray) {     System.out.println(o); } 
like image 23
Edward Q. Bridges Avatar answered Sep 23 '22 11:09

Edward Q. Bridges