24

I know how to do the toString method for one dimensional arrays of strings, but how do I print a two dimensional array? With 1D I do it this way:

public String toString() {
    StringBuffer result = new StringBuffer();
    res = this.magnitude;

    String separator = "";
    if (res.length > 0) {
        result.append(res[0]);
        for (int i=1; i<res.length; i++) {
            result.append(separator);
            result.append(res[i]);
        }
    }
return result.toString();

How can I print a 2D array?

1
  • If you are in a single-threaded environment, the StringBuilder class should generally be used in preference to StringBuffer as it supports all of the same operations but it is faster, as it performs no synchronization. Commented Mar 7, 2010 at 19:23

5 Answers 5

79

The Arrays class defines a couple of useful methods

  • Arrays.toString - which doesn't work for nested arrays
  • Arrays.deepToString - which does exactly what you want

 

String[][] aastr = {{"hello", "world"},{"Goodbye", "planet"}};
System.out.println(Arrays.deepToString(aastr));

Gives

  [[hello, world], [Goodbye, planet]]
Sign up to request clarification or add additional context in comments.

1 Comment

10 years and I never heard of deepToString. Facepalm
6

You just iterate twice over the elements:

StringBuffer results = new StringBuffer();
String separator = ","
float[][] values = new float[50][50];

// init values

for (int i = 0; i < values.length; ++i)
{
  result.append('[');
  for (int j = 0; j < values[i].length; ++j)
    if (j > 0)
      result.append(values[i][j]);
    else
      result.append(values[i][j]).append(separator);
  result.append(']');
}

IMPORTANT: StringBuffer are also useful because you can chain operations, eg: buffer.append(..).append(..).append(..) since it returns a reference to self! Use synctactic sugar when available..

IMPORTANT2: since in this case you plan to append many things to the StringBuffer it's good to estimate a capacity to avoid allocating and relocating the array many times during appends, you can do it calculating the size of the multi dimensional array multiplied by the average character length of the element you plan to append.

3 Comments

Method chaining has nothing to do with syntactic sugar; it's an API feature, not a language feature. Otherwise, +1.
you could use StringBuilder which is not synchronized and could be faster under some circumstances
Yep, I knew about it. Synctactic sugar should regard the syntax (grammar) of the language while this is just a method of the class.. but no other term came into my mind, see it as a poetic license :)
2
public static <T> String to2DString(T[][] x) {
    final String vSep = "\n";
    final String hSep = ", ";
    final StringBuilder sb = new StringBuilder();

    if(x != null)
    for(int i = 0; i < x.length; i++) {
        final T[] a = x[i];
        if(i > 0) {
            sb.append(vSep);
        }
        if(a != null)
        for(int j = 0; j < a.length; j++) {
            final T b = a[j];
            if(j > 0) {
                sb.append(hSep);
            }
            sb.append(b);
        }
    }
    return sb.toString();
}

1 Comment

This is problematic if the array contains multiple references that are ==. For example, it wouldn't work with new String[][] {{"1", "1"}, {"1", "1"}} because of interning. Bad technique, in my opinion.
0

Two for loops:

for (int i=1; i<res.length; i++) {
    for (int j=1; j<res[i].length; j++) {
        result.append(separator);
        result.append(res[i][j]);
    }
}

Comments

0
public static void main(String[] args) {

    String array [] [] = {
        {"*","*", "*", "*", "*", "*"},
        {"*"},
        {"*"},
        {"*"},
        {"*","*", "*", "*", "*", "*"},
        {"*"},
        {"*"},
        {"*"},
        {"*"},
        {"*"}};


    for (int row=0; row<array.length;row++) {

        for (int column = 0; column < array[row].length; column++) {
            System.out.print(array[row][column]);
        }
        System.out.println();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.