在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]

当前回答

在java 8中:

Arrays.stream(myArray).forEach(System.out::println);

其他回答

可以选择使用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>

这是一种非常简单的方法来打印数组,而不使用JAVA中的任何循环。->对于,单个或简单阵列:int[]数组=新int[]{1,2,3,4,5,6};System.out.println(数组.toString(数组));输出:[1, 2, 3, 4, 5, 6]->因此,这个2D数组不能用Arrays.toString()打印int[][]array=newint[][][]{{1,2,3,4,5,6,7},{8,9,10,11,12,13,14}};System.out.println(数组.depToString(数组));输出:[[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]]

如果您使用的是Java 11

import java.util.Arrays;
public class HelloWorld{

     public static void main(String []args){
        String[] array = { "John", "Mahta", "Sara" };
       System.out.println(Arrays.toString(array).replace(",", "").replace("[", "").replace("]", ""));
     }
}

输出:

John Mahta Sara

从Java5开始,您可以对数组中的数组使用Arrays.toString(arr)或Arrays.deepToString(arr)。注意,Object[]版本对数组中的每个对象调用.toString()。输出甚至按照您要求的方式进行装饰。

示例:

简单阵列:String[]数组=新String[]{“John”,“Mary”,“Bob”};System.out.println(数组.toString(数组));输出:[约翰、玛丽、鲍勃]嵌套数组:String[][]deepArray=新String[][]{{“John”,“Mary”},{“Alice”,“Bob”}};//产生不希望的输出:System.out.println(Arrays.toString(deepArray));//给出所需输出:System.out.println(Array.deepToString(deepArray));输出:[[Ljava.lang.String;@106d69c,[Ljava.lang.String;@52e922][[约翰,玛丽],[爱丽丝,鲍勃]]双阵列:double[]doubleArray={7.0,9.0,5.0,1.0,3.0};System.out.println(Arrays.toString(doubleArray));输出:[7.0, 9.0, 5.0, 1.0, 3.0 ]int数组:int[]intArray={7,9,5,1,3};System.out.println(数组.toString(intArray));输出:[7, 9, 5, 1, 3 ]

使用Arrays类。它有多个实用程序方法,其toString()被重写为以人类可读的方式显示数组元素。数组.toString(arr)