For example, I have the array
int [] array = new int[2];
using code
for (int i: array){
System.out.println(i);
};
I see the output 0 and 0, it's expected
but what if I want to output the multi-array:
int [][] array2 = new int[2]\[2];
for (int[] i : array2) {
for(int[] j : array2 ){
System.out.println(Arrays.toString(array2));
}
System.out.println(Arrays.toString(array2));
};
I have strange output
[[I@7d4991ad, [I@28d93b30]
[[I@7d4991ad, [I@28d93b30]
[[I@7d4991ad, [I@28d93b30]
[[I@7d4991ad, [I@28d93b30]
[[I@7d4991ad, [I@28d93b30]
[[I@7d4991ad, [I@28d93b30]
but expected result for me is
0 0
0 0
CodePudding user response:
You have an array of arrays, so each index in array2
contains another array that is an object itself. What you get back your way is the memory address of this object.
An easy way to print the array the way you want it would be the following:
for (int i = 0; i < array.length; i ) {
for(int j = 0; i < array.length; j ){
System.out.println(array[i][j]);
}
};
CodePudding user response:
This should help to print
for (int[] row : array2) {
System.out.println(Arrays.toString(row));
}
Output
[0, 0]
[0, 0]
CodePudding user response:
I believe you will have to use the length property of the array and an indexed var vs a foreach approach.
https://www.softwaretestinghelp.com/multidimensional-arrays-in-java/