user1529540
user1529540

Reputation:

What is the best way to print a multidimensional array in java?

I recently started mutltidimensional int arrays in java. Before that one dimensional arrays had sufficed.

To print those I used System.out.println(Arrays.toString(myarray));

But it won't work with multi dimensional arrays, it does the same thing as it does when you try to print a one dimensional array directly only many times.

Upvotes: 4

Views: 1166

Answers (4)

Michael Goldstein
Michael Goldstein

Reputation: 618

You'll need to iterate through it.

The easiest way to do so is to use the provided Arrays.deepToString() which searches for arrays within the array. Note that it, like Arrays.toString(), is only available in Java 1.5+ although I certainly hope that you are using Java 5 by now.

For example:

int[][] myArray = { { 1, 2, 3 }, { 4, 5, 6 } };
System.out.println(Arrays.deepToString(myArray));

Alternatively, you can iterate yourself which also allows for more customization with the style in which you choose to print.

For example:

int[][] myArray = { { 1, 2, 3 }, { 4, 5, 6 } };
for(int[] arr : myArray)
    System.out.println(Arrays.toString(arr));

Upvotes: 10

Jorge Aguilar
Jorge Aguilar

Reputation: 3450

you can easily iterate trough the array like this:

if (yourArray != null) {
    // Where object type means the type of your array.
    for (ObjectType subArray : yourArray) {
        // If this method can't receive nulls, then validate that subArray isn't null
        System.out.println(Arrays.toString(subArray));
    }
}

Upvotes: 0

antonycc
antonycc

Reputation: 76

Try Commons Lang 3's ArrayUtils toString method:

   @Test
   public void multiArrayToString(){
      int[] a = {1,2,3};
      int[] b = {4,5,6};
      int[][] c = {a, b};
      String aCommonsLangToString = ArrayUtils.toString(a);
      String bCommonsLangToString = ArrayUtils.toString(b);
      String cCommonsLangToString = ArrayUtils.toString(c);
      System.out.println(aCommonsLangToString);
      System.out.println(bCommonsLangToString);
      System.out.println(cCommonsLangToString);
   }

Output:

{1,2,3}
{4,5,6}
{{1,2,3},{4,5,6}}

Upvotes: 0

SMA
SMA

Reputation: 37023

Try something like:

int number[][] = { {1, 2, 3}, {1}, {2}};
for (int i = 0; i < number.length; i++)
    System.out.println(Arrays.toString(number[i]));

Upvotes: 0

Related Questions