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?
You just iterate twice over the elements:
IMPORTANT:
StringBufferare 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
StringBufferit’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.