Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Monday, November 19, 2007

java.util.Arrays.toString(...) for debugging

AVOID default toString(). Using the common debugging technique of printing intermediate values on the console with arrays is good, but requires calling a library method to get the results you expect. Arrays are a subclass of Object as ever other object is, and therefore the toString() method is defined for every array. The results will very likely disappoint you.

String[] abc = {"a", "b", "c"};
System.out.println(abc); // println calls toString() on object parameters.

This displays the relatively unhelpful "[L", element type, ";@", and hexadecimal memory address of the array.

[Ljava.lang.String;@f6f1b6

USE java.util.Arrays.toString(...) and you'll get something much more readable. An import java.util.*; statement avoids the extra package qualifier.

String[] abc = {"a", "b", "c"};
System.out.println(java.util.Arrays.toString(abc));

This produces the following output, which is the same as toString() applied to a List.

[a, b, c]

No comments:

Post a Comment

Archives