Print array content with Arrays.toString or Arrays.asList

When directly printing an array, it gives its element type and hashcode, which is not the desired result in most cases. A better way is to use java.util.Arrays.toString(), or Arrays.asList() method to print the string representation of the array.

This test method tries 2 ways of printing the content of a string array:
public final void testPrintArray() {
final String[] names = {"Linux", "Mac OS X", "Windows", "Solaris", null};
System.out.println("print names array directly: " + names);
System.out.println("print names with Arrays.toString(): " + Arrays.toString(names));
System.out.println("print names with Arrays.asList(): " + Arrays.asList(names));
}
Test output:
print names array directly: [Ljava.lang.String;@5122cdb6
print names with Arrays.toString(): [Linux, Mac OS X, Windows, Solaris, null]
print names with Arrays.asList(): [Linux, Mac OS X, Windows, Solaris, null]
Between the 2 methods, I find toString() is more natural. Arrays.toString() was introduced in Java 5, somewhat later than Arrays.asList().

Also note that a List can take null as element value, and its string representation is "null".

Followers

Pageviews Last 7 Days