打印 Java 数组的最简单方法是什么? [英] What's the simplest way to print a Java array?
问题描述
在 Java 中,数组不会覆盖 toString()
,所以如果你尝试直接打印一个,你会得到 className
+ '@' + 的十六进制数组的 hashCode
,由 定义Object.toString()
:
In Java, arrays don't override toString()
, so if you try to print one directly, you get the className
+ '@' + the hex of the hashCode
of the array, as defined by 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]
的东西.最简单的方法是什么?以下是一些示例输入和输出:
But usually, we'd actually want something more like [1, 2, 3, 4, 5]
. What's the simplest way of doing that? Here are some example inputs and outputs:
// 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 5 开始,您可以使用 Arrays.toString(arr)
或 Arrays.deepToString(arr)
对于数组中的数组.请注意,Object[]
版本对数组中的每个对象调用 .toString()
.输出甚至按照您要求的方式进行修饰.
Since Java 5 you can use Arrays.toString(arr)
or Arrays.deepToString(arr)
for arrays within arrays. Note that the Object[]
version calls .toString()
on each object in the array. The output is even decorated in the exact way you're asking.
示例:
简单数组:
String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));
输出:
[John, Mary, Bob]
嵌套数组:
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
输出:
[[John, Mary], [Alice, Bob]]
double
数组:
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(Arrays.toString(intArray));
输出:
[7, 9, 5, 1, 3 ]
这篇关于打印 Java 数组的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!