Elegant Printing of Java Collections: From Default toString to Arrays.toString Conversion

Nov 26, 2025 · Programming · 11 views · 7.8

Keywords: Java Collections | toString Method | Arrays.toString | Stack Printing | Debug Output

Abstract: This paper thoroughly examines the issue of unfriendly output from Java collection classes' default toString methods, with a focus on printing challenges for Stack<Integer> and other collections. By comparing the advantages of the Arrays.toString method, it explains in detail how to convert collections to arrays for aesthetic output. The article also extends the discussion to similar issues in Scala, providing universal solutions for collection printing across different programming languages, complete with code examples and performance analysis.

Problem Background and Current Situation Analysis

In Java programming practice, developers often encounter the issue of un intuitive output from collection objects. Taking Stack<Integer> as an example, directly calling its toString() method produces default object identifiers like java.util.Stack@15db9742, rather than the expected [1,2,3...] format. This output style stems from the design philosophy of the Java Collections Framework: the toString() method inherits from the Object class and defaults to returning a combination of the class name and hash code.

Core Solution: Array Conversion Method

The most effective solution is to utilize the Arrays.toString() method in the Java standard library. This method is specifically designed for elegant array output, automatically handling separators between elements and overall formatting. The specific implementation code is as follows:

import java.util.Arrays;
import java.util.Stack;

public class PrettyPrintExample {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        
        // Traditional way: unfriendly output
        System.out.println("Default: " + stack);
        
        // Optimized way: via array conversion
        System.out.println("Pretty: " + Arrays.toString(stack.toArray()));
    }
}

After executing the above code, the first output is Default: [1, 2, 3] (actually, Stack's toString has been overridden, but other collections like HashSet still have issues), and the second output is Pretty: [1, 2, 3]. The key is that stack.toArray() converts the collection elements into an Object array, and then Arrays.toString() is responsible for the neatly formatted output.

In-depth Technical Principle Analysis

The internal implementation of the Arrays.toString() method is based on recursive traversal and string builders:

// Simplified Arrays.toString implementation principle
public static String toString(Object[] a) {
    if (a == null) return "null";
    
    int iMax = a.length - 1;
    if (iMax == -1) return "[]";
    
    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(String.valueOf(a[i]));
        if (i == iMax) {
            b.append(']');
            return b.toString();
        }
        b.append(", ");
    }
}

This design ensures the uniformity and readability of the output format. Regardless of the array element types, it can generate a standard string representation enclosed in square brackets and separated by commas.

Cross-language Comparison: Similar Issues in Scala

The Scala case mentioned in the reference article reveals the universality of similar problems. In Scala 2.13, the mapValues operation returns a MapView object, and direct printing produces unfriendly output like [Lscala.Tuple2;@724a1b65. This is essentially the same as the default toString issue with Java collections.

Scala's solution is to convert the view to a concrete collection via the toMap or toArray methods:

// Scala example: solving MapView printing issue
val result = tale.groupBy(identity).view.mapValues(_.size).toMap
println(result) // outputs friendly HashMap format

This further validates that "converting lazy computation views to concrete collections" is a universal pattern for solving printing problems.

Performance Considerations and Best Practices

When using the Arrays.toString(stack.toArray()) method, attention must be paid to performance impacts:

Alternative solutions include custom output methods or using third-party libraries like Apache Commons Lang's ToStringBuilder.

Extended Applications and Summary

The method introduced in this article applies to all Java collection types, including List, Set, Queue, etc. The key is understanding the interoperability between collections and arrays, and the formatting capability of Arrays.toString().

By converting collections to arrays and then using Arrays.toString(), developers can achieve output effects comparable to the Eclipse debugger, significantly improving the readability of code debugging and log output. This method is simple and effective, serving as the standard solution for Java collection printing issues.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.