springcloudlearner
springcloudlearner

Reputation: 457

Java Three D Array in for loop

m1 method has 3-d array as argument, also printing b (object reference) gives [[[I@15db9742 which implies that a is 3-d array but in for loop (bold) a is behaving as 2-d array, if i write it as int x[][][]:a then it is

giving error " Type mismatch: cannot convert from element type int[][] to 
     int[][][]"

What is the reason of this behavior ?

public class Arr {

    public static void main(String[] args) {

        int[][][] aa2=new int[2][1][];

        m1(aa2);
    }

    public static void m1(int[][][] b)
    {
        **for(int[][] x:b)**
        System.out.println(b);

    }
}

Upvotes: 2

Views: 195

Answers (3)

Honza Zidek
Honza Zidek

Reputation: 20036

There is no such thing as "3D array" in Java. It is a false friend to former C/C++ programmers, it looks the same but it is something completely different.

An array in Java is always 2D. It does not even have the "dimensions", actually each "row" can contain different number of "columns".

Please study the Oracle tutorial on arrays.

Your array in fact might look like this:

  • yellow: first "dimension", contains references to int[][]
  • blue: second "dimension", contains references to int[]
  • green: third "dimension", contains directly the int numbers

enter image description here

Upvotes: 1

Izruo
Izruo

Reputation: 2276

I think you misunderstand the enhanced for loop syntax.

You do not have to re-declare the array-variable itself, but instead explicitly declare the type of elements you are expecting from the iteration.

int[] array;
for (      String             element       :     array)
//     element type  ||  element variable  ||  array variable

Note the String[] vs String.

  • String[] array declares the array variable you are iterating over.
  • String element declares the element type you are expecting. You can also declare Object element, as String is a subclass of Object.

Now, as already elaborated in other questions, a '3-d array' does not actually exist in java, but it is merely an array of arrays of arrays - or in other words an array of '2-d arrays'.

This is why the following syntax is required in the example you provided:

int[][][] array;
for (int[][] element : array)

Upvotes: 0

Dennis Kriechel
Dennis Kriechel

Reputation: 3749

You for-loop is not correct. What you are doing is iteration over the array b which is int[][][] (you called it the 3D-Array) to get the next lower layer int[][].

But then you used System.out.println(b); which is not printing out your int[][] but the int[][][] that was passed to your method, basicly the for-loop is never used.

This would do the job:

public static void m1(int[][][] b)
{
    for(int[][] x : b)
       System.out.println(x);

}

Result:

[[I@15db9742
[[I@6d06d69c

Upvotes: 1

Related Questions