Java如何打印数组变量的内容?

您需要打印数组变量的内容。解决这个问题的长途方法是使用循环来打印数组的每个元素。为了简化此过程,您可以使用Apache Commons LangArrayUtils.toString()方法。此方法可以将任何数组作为参数,并打印出用逗号分隔并用大括号括起来的内容。当需要在数组为时打印特定的字符串时null,可以string为该方法提供第二个参数。

package org.nhooo.example.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayUtilsToString {
    public static void main(String[] args) {
        // 将int数组打印为字符串。
        int[] numbers = {1, 2, 3, 5, 8, 13, 21, 34};
        System.out.println("Numbers = " + ArrayUtils.toString(numbers));

        // 将字符串数组打印为字符串。
        String[] grades = {"A", "B", "C", "D", "E", "F"};
        System.out.println("Grades = " + ArrayUtils.toString(grades));

        // 将多维数组打印为字符串。
        int[][] matrix = {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}};
        System.out.println("Matrix = " + ArrayUtils.toString(matrix));

        // 当数组为null时,返回“ Empty”。"Empty" when the array is null.
        String[] colors = null;
        System.out.println("Colors = " + ArrayUtils.toString(colors, "None"));
    }
}

上面的代码片段的输出:

Numbers = {1,2,3,5,8,13,21,34}
Grades = {A,B,C,D,E,F}
Matrix = {{0,1,2},{1,2,3},{2,3,4}}
Colors = None

如果您使用的是JDK 1.5或更高版本,则实际上可以使用java.util.Arrays该类执行与该类相同的org.apache.commons.lang.ArrayUtils操作。

Maven依赖

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

Maven中央