Friday, November 19, 2004

Print out all members of a collection in JDK 5.0

In JDK 5.0, there is a new Arrays class which provides a deepToString() method, which will print out all members of an array.

For example, the following code will printout the multi-dimensional array values:

String[][] strings = {{"I", "love", "lucy"}, {"I", "hate", "bart"};
System.out.println(Arrays.deepToString(strings));

The output of the code above is:

[[I, love, lucy], [I, hate, bart]]

One can use the same method to print out single-dimension collections such as ArrayList and HashSet. The below examples show how to do get the printout:

// print out all members of a vector
System.out.println(Arrays.deepToString(vector.toArray(new Object[0]))));

// print out all members of a hash set
System.out.println(Arrays.deepToString(set.toArray())));