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( ) ) );
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access