views:

98

answers:

4

I know how to do toString method for one dimensional arrays of strings, but how to print 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 to print 2D array.

+1  A: 

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]);
    }
}
Felix Kling
+2  A: 

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.

Jack
Method chaining has nothing to do with syntactic sugar; it's an API feature, not a language feature. Otherwise, +1.
polygenelubricants
you could use StringBuilder which is not synchronized and could be faster under some circumstances
Karussell
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 :)
Jack
+2  A: 
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();
}
Pindatjuh
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.
polygenelubricants
True, while works in most cases. Fixing now.
Pindatjuh
+11  A: 

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]]
Robert Christie