在Java中,数组不会重写toString(),因此如果您尝试直接打印一个,则会得到数组的className+“@”+hashCode的十六进制,如Object.toString()所定义:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // Prints something like '[I@3343c8b3'

但通常情况下,我们会想要更像[1,2,3,4,5]的东西。最简单的方法是什么?以下是一些输入和输出示例:

// Array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};
// Output: [1, 2, 3, 4, 5]

// Array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};
// Output: [John, Mary, Bob]

当前回答

可以选择使用org.apache.commons.lang3.StringUtils.join(*)方法例如:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

我使用了以下依赖项

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>

其他回答

Arrays.deepToString(arr)只打印一行。

int[][] table = new int[2][2];

要将表格打印为二维表格,我必须执行以下操作:

System.out.println(Arrays.deepToString(table).replaceAll("],", "]," + System.getProperty("line.separator")));

看起来Array.deepToString(arr)方法应该使用分隔符字符串,但不幸的是它没有。

如果您正在运行jdk 8。

public static void print(int[] array) {
    StringJoiner joiner = new StringJoiner(",", "[", "]");
    Arrays.stream(array).forEach(element -> joiner.add(element + ""));
    System.out.println(joiner.toString());
}


int[] array = new int[]{7, 3, 5, 1, 3};
print(array);

输出:

[7,3,5,1,3]

可以选择使用org.apache.commons.lang3.StringUtils.join(*)方法例如:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

我使用了以下依赖项

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>

有以下方法打印阵列

 // 1) toString()  
    int[] arrayInt = new int[] {10, 20, 30, 40, 50};  
    System.out.println(Arrays.toString(arrayInt));

// 2 for loop()
    for (int number : arrayInt) {
        System.out.println(number);
    }

// 3 for each()
    for(int x: arrayInt){
         System.out.println(x);
     }

从Java 8开始,还可以利用String类提供的join()方法打印出数组元素,不带括号,并用分隔符分隔(这是下面示例中的空格字符):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

输出将是“嘿,朋友!”。