Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach with multidimensional arrays in Java

Tags:

java

I read Java: The Complete Reference(9th). In Character 5: Control Statements - Iterating Over Multidimensional Arrays section Write:

The enhanced version of the for also works on multidimensional arrays. Remember, however, that in Java, multidimensional arrays consist of arrays of arrays. (For example, a two-dimensional array is an array of one-dimensional arrays.) This is important when iterating over a multidimensional array, because each iteration obtains the next array, not an individual element. Furthermore, the iteration variable in the for loop must be compatible with the type of array being obtained. For example, in the case of a two-dimensional array, the iteration variable must be a reference to a one-dimensional array. In general, when using the for-each for to iterate over an array of N dimensions, the objects obtained will be arrays of N–1 dimensions. To understand the implications of this, consider the following program. It uses nested for loops to obtain the elements of a two-dimensional array in row- order, from first to last.

I can't understand why "to iterate over an array of N dimensions, the objects obtained will be arrays of N–1 dimensions". Is it true?

like image 413
Axifive Avatar asked Feb 25 '15 14:02

Axifive


People also ask

Can we use for each for multidimensional array in Java?

Use foreach(for each) style for on a two-dimensional array. : Foreach « Language Basics « Java. Use foreach(for each) style for on a two-dimensional array.

Can we use foreach loop for 2D array?

Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array.

How do you print a 2D array for each loop?

Code: public class Print2DArrayInJava { public static void main(String[] args) { //below is declaration and intialisation of a 2D array final int[][] matrx = { { 11, 22}, { 41, 52}, }; for (int r = 0; r < matrx. length; r++) { //for loop for row iteration. for (int c = 0; c < matrx[r].

How do you loop through a multidimensional array?

Looping through multidimensional arrays Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. To do this, you need to create nested foreach loops — that is, one loop inside another: The outer loop reads each element in the top-level array.


1 Answers

An array of N dimensions is really an array of (N-1)-dimensional arrays. Therefore, when we iterate over an array of N dimensions, we are iterating over all of its constituent (N-1)-dimensional arrays, as indicated.

For example, consider a 2-dimensional array:

int[][] array = {{1,2,3}, {4,5,6}};

This is really an array of 1-dimensional arrays: {1,2,3} and {4,5,6}.

like image 119
arshajii Avatar answered Oct 25 '22 10:10

arshajii