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

当前回答

toString是一种将数组转换为字符串的方法。

此外,您还可以使用:

for (int i = 0; i < myArray.length; i++){
System.out.println(myArray[i] + " ");
}

此for循环将使您能够按顺序打印数组的每个值。

其他回答

for(int n: someArray) {
    System.out.println(n+" ");
}

这是一种非常简单的方法来打印数组,而不使用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]]

您可以循环遍历数组,在循环时打印出每个项。例如:

String[] items = {"item 1", "item 2", "item 3"};

for(int i = 0; i < items.length; i++) {

    System.out.println(items[i]);

}

输出:

item 1
item 2
item 3

通过使用java.util.Arrays:

String mRole = "M_XXX_ABC";        
System.out.println(Arrays.asList(mRole.split("_")).toString());

输出:[M,XXX,ABC]

在JDK1.8中,可以使用聚合运算和lambda表达式:

String[] strArray = new String[] {"John", "Mary", "Bob"};

// #1
Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));

// #2
Stream.of(strArray).forEach(System.out::println);

// #3
Arrays.stream(strArray).forEach(System.out::println);

/* output:
John
Mary
Bob
*/