1.8. Printing an Array

Problem

You need to print the contents of an array.

Solution

Use ArrayUtils.toString() to print the contents of an array. This method takes any array as an argument and prints out the contents delimited by commas and surrounded by brackets:

int[] intArray = new int[] { 2, 3, 4, 5, 6 };

int[] multiDimension = new int[][] { { 1, 2, 3 }, { 2, 3 }, {5, 6, 7} };

System.out.println( "intArray: " + ArrayUtils.toString( intArray ) );
System.out.println( "multiDimension: " + ArrayUtils.
toString( multiDimension ) );

This example takes two arrays and prints them out using ArrayUtils.toString( ):

intArray: {2,3,4,5,6}
multiDimension: {{1,2,3},{2,3},{5,6,7}}

Discussion

This simple utility can be used to print the contents of an Object[], substituting an object for a null element:

String[] strings = new String[] { "Blue", "Green", null, "Yellow" };

System.out.println( "Strings: " + ArrayUtils.toString( strings, "Unknown" );

This example prints the strings array, and when ArrayUtils encounters a null element, it will print out “Unknown”:

Strings: {Blue,Green,Unknown,Yellow}

This utility comes in handy when you need to print the contents of a Collection for debugging purposes. If you need to print out the contents of a Collection, convert it to an array, and pass that array to ArrayUtils.toString():

List list = new ArrayList( );
list.add( "Foo" );
list.add( "Blah" );

System.out.println( ArrayUtils.toString( list.toArray( ) ) );
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.199