Drawing Hands by M.C. Escher (1948)

Jeff Mesnil


Stringified representation of arrays in Java

On November 8th, 2004 in java

When you call the toString() method on an array in Java, you don’t get an useful representation:

Object[] foo = {"bar", "baz"};
System.out.println(foo);

>>> [Ljava.lang.Object;@e0b6f5

I used to create my own representation of the array:

StringBuffer buff = new StringBuffer("[");
for (int i = 0; i < foo.length; i++) {
   if (i > 0) {
      buff.append(", ");
   }
   buff.append(foo[i]);
}
buff.append("]");
System.out.println(buff.toString());

>>> ["bar", "baz"]

But I recently discovered that the Collections Framework already offers this function:

System.out.println(Arrays.asList(foo));

>>> ["bar", "baz"]

The trick is that you rely on the stringified representation of a List to get the stringified representation of the array.

3 Responses to “Stringified representation of arrays in Java”

  1. Anonymous Says:

    In 1.5 you can use
    System.out.println(Arrays.deepToString(a));

    which works for nested and primitive arrays also.

    Chris

  2. jmesnil Says:

    thanks for the tip Chris!

    I just need to wait for Apple to release Java 1.5 to try it! :-)

  3. i Says:

    I wonder why anyone would use arrays in favour of Lists in the first place…