在 Java 中,数组不会覆盖toString(),因此如果您尝试直接打印一个,您会得到className+ ‘@’ +hashCode数组的十六进制值,定义如下Object.toString():
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]. 最简单的方法是什么?以下是一些示例输入和输出:
[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 5 开始,您可以在数组中使用Arrays.toString(arr)orArrays.deepToString(arr)来表示数组。请注意,Object[]版本调用.toString()数组中的每个对象。输出甚至以您要求的确切方式进行装饰。
Arrays.toString(arr)
Arrays.deepToString(arr)
Object[]
.toString()
例子:
java String[] array = new String[] {"John", "Mary", "Bob"}; System.out.println(Arrays.toString(array));
输出:
java [John, Mary, Bob]
java 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));
java [[John, Mary], [Alice, Bob]]
double
java double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 }; System.out.println(Arrays.toString(doubleArray));
java [7.0, 9.0, 5.0, 1.0, 3.0 ]
int
java int[] intArray = { 7, 9, 5, 1, 3 }; System.out.println(Arrays.toString(intArray));
java [7, 9, 5, 1, 3 ]