Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print multi-dimensional array using foreach [duplicate]

How to print multi-dimensional array using for-each loop in java? I tried, foreach works for normal array but not work in multi-dimensional array, how can I do that? My code is:

class Test
{
   public static void main(String[] args)
   {
      int[][] array1 = {{1, 2, 3, 4}, {5, 6, 7, 8}};
      for(int[] val: array1)
      {
        System.out.print(val);
      }
   } 
}
like image 474
Santhoshkumar Sivaji Avatar asked Oct 06 '12 14:10

Santhoshkumar Sivaji


1 Answers

Your loop will print each of the sub-arrays, by printing their address. Given that inner array, use an inner loop:

for(int[] arr2: array1)
{
    for(int val: arr2)
        System.out.print(val);
}

Arrays don't have a String representation that would, e.g. print all the elements. You need to print them explicitly:

int oneD[] = new int[5];
oneD[0] = 7;
// ...

System.out.println(oneD);

The output is an address:

[I@148cc8c

However, the libs do supply the method deepToString for this purpose, so this may also suit your purposes:

System.out.println(Arrays.deepToString(array1));
like image 112
pb2q Avatar answered Sep 23 '22 17:09

pb2q