Arrays as String

Logging the contents of a Collection is simple, since AbstractCollection.toString is always available. For an array, however, the default toString method is not very informative, and doesn't include the array contents.

To provide more useful representations of arrays, various toString methods (and the deepToString method) were added to the Arrays class in JDK 1.5. Those methods can be used when available, as in:

Arrays.toString(myArray); 
Arrays.deepToString(myObjectArray); //recursive

If you need an alternative, you can simply convert the array to a collection, as in

Arrays.asList(myArray).toString();

Finally, here's a third option, using a utility class which:


import java.lang.reflect.Array;

/**
* Convenience method for producing a simple textual
* representation of an array.
*
* <P>The format of the returned <code>String</code> is the same as
* <code>AbstractCollection.toString</code>:
* <ul>
*  <li>non-empty array: [blah, blah]
*  <li>empty array: []
*  <li>null array: null
* </ul>
*
* @author Jerome Lacoste
* @author www.javapractices.com
*/
public final class ArrayToString {

  /**
  * <code>aArray</code> is a possibly-null array whose elements are
  * primitives or objects; arrays of arrays are also valid, in which case
  * <code>aArray</code> is rendered in a nested, recursive fashion.
  */
  public static String get(Object array){
    if (array == null) return NULL;
    checkObjectIsArray(array);

    StringBuilder result = new StringBuilder(START_CHAR);
    int length = Array.getLength(array);
    for (int idx = 0 ; idx < length ; ++idx) {
      Object item = Array.get(array, idx);
      if (isNonNullArray(item)){
        //recursive call!
        result.append(get(item));
      }
      else{
        result.append(item);
      }
      if (! isLastItem(idx, length)) {
        result.append(SEPARATOR);
      }
    }
    result.append(END_CHAR);
    return result.toString();
  }

  // PRIVATE
  private static final String START_CHAR = "[";
  private static final String END_CHAR = "]";
  private static final String SEPARATOR = ", ";
  private static final String NULL = "null";

  private static void checkObjectIsArray(Object array){
    if (! array.getClass().isArray()) {
      throw new IllegalArgumentException("Object is not an array.");
    }
  }

  private static boolean isNonNullArray(Object item){
    return item != null && item.getClass().isArray();
  }

  private static boolean isLastItem(int idx, int length){
    return (idx == length - 1);
  }

  /** Test harness.  */
  public static void main(String... args) {
    boolean[] booleans = {true, false, false};
    char[] chars = {'B', 'P', 'H'};
    byte[] bytes = {3};
    short[] shorts = {5,6};
    int[] ints = {7,8,9,10};
    long[] longs = {100,101,102};
    float[] floats = { 99.9f, 63.2f};
    double[] doubles = { 212.2, 16.236, 42.2};
    String[] strings = {"blah", "blah", "blah"};
    java.util.Date[] dates = { new java.util.Date(), new java.util.Date() };
    log("booleans: " + get(booleans));
    log("chars: " + get(chars));
    log("bytes: " + get(bytes));
    log("shorts: " + get(shorts));
    log("ints: " + get(ints));
    log("longs: " + get(longs));
    log("floats: " + get(floats));
    log("double: " + get(doubles));
    log("strings: " + get(strings));
    log("dates: " + get(dates));

    int[] nullInts = null;
    int[] emptyInts = {};
    String[] emptyStrings = {"", ""};
    String[] nullStrings = {null, null};
    log("null ints: " + get(nullInts));
    log("empty ints: " + get(emptyInts));
    log("empty Strings: " + get(emptyStrings));
    log("null Strings: " + get(nullStrings));

    String[] arrayA = {"A", "a"};
    String[] arrayB = {"B", "b"};
    String[][] arrayOfArrays = {arrayA, arrayB};
    log("array Of Arrays: " + get(arrayOfArrays));
  }
  
  private static void log(String msg) {
    System.out.println(msg);
  }
} 

An example run of this class:

>java -cp . ArrayToString
booleans: [true, false, false]
chars: [B, P, H]
bytes: [3]
shorts: [5, 6]
ints: [7, 8, 9, 10]
longs: [100, 101, 102]
floats: [99.9, 63.2]
double: [212.2, 16.236, 42.2]
strings: [blah, blah, blah]
dates: [Wed Jun 18 09:55:08 EDT 2003, Wed Jun 18 09:55:08 EDT 2003]
null ints: null
empty ints: []
empty Strings: [, ]
null Strings: [null, null]
array Of Arrays: [[A, a], [B, b]]

See Also :
Implementing toString