Course contentsShow
← Java
Lesson 540 of 2,87013. The Object Class and Common MethodsFree lesson

toString in Collections and Arrays

Explore how toString behaves with collections, arrays, and when to use Arrays.toString or deepToString.

toString in Collections and Arrays

You'll learn how toString behaves differently for collections versus arrays, and when to use special helper methods.

The Collection Advantage

When you call toString on most Java collections (like ArrayList, HashSet, or HashMap), you get a clean, readable representation automatically:

List<String> colors = new ArrayList<>();
colors.add("red");
colors.add("blue");
System.out.println(colors);  // Output: [red, blue]

Collections override toString to display their elements in a human-friendly format. The Java library designers did this work for you!

The Array Problem

Arrays, however, do not override toString. Calling toString on an array gives you the default Object implementation—a cryptic memory address:

String[] colors = {"red", "blue"};
System.out.println(colors);  // Output: [Ljava.lang.String;@15db9742

Not helpful at all!

The Solution: Arrays.toString

Use the static helper method Arrays.toString to get readable output:

String[] colors = {"red", "blue"};
System.out.println(Arrays.toString(colors));  // Output: [red, blue]

For Nested Arrays: Arrays.deepToString

If you have multidimensional arrays or arrays containing arrays, use Arrays.deepToString:

int[][] matrix = {{1, 2}, {3, 4}};
System.out.println(Arrays.toString(matrix));      // Bad: [[I@hash, [I@hash]
System.out.println(Arrays.deepToString(matrix));  // Good: [[1, 2], [3, 4]]

Think of it this way: collections are like smart boxes that know how to describe their contents, while arrays are like plain containers that need external help to explain what's inside them.

Key Takeaway: Collections automatically provide readable toString output, but arrays require Arrays.toString or Arrays.deepToString for human-friendly representation—remember to use these helper methods when debugging or logging array contents.