什么是打印Java数组最简单的方法? [英] What's the simplest way to print a Java array?
问题描述
在Java中,数组不覆盖的toString()
,因此,如果您尝试直接打印一个,你得到奇怪的输出,包括内存位置:
INT [] intArray = INT新[] {1,2,3,4,5};
的System.out.println(intArray); //打印像[我@ 3343c8b3
但通常我们预期的要像更多的东西[1,2,3,4,5]
。什么是这样做的最简单的方法?下面是一些例子输入和输出:
//阵元组成:
INT [] intArray =新INT [] {1,2,3,4,5};
//输出:[1,2,3,4,5]//对象引用数组:
的String [] = strArray新的String [] {约翰,玛丽,鲍勃};
//输出:[约翰,玛丽,鲍勃]
由于Java 5中,您可以用 Arrays.toString(ARR)
或阵列.deepToString(ARR)
数组内的数组。请注意,对象[]
版本调用的ToString()
数组中的每个对象。输出即使是在装饰你问的具体方式。
例如:
简单数组:
String []数组=新的String [] {约翰,玛丽,鲍勃};
的System.out.println(Arrays.toString(阵列));
输出:
[约翰,玛丽,鲍勃]
嵌套数组:
的String [] [] = deepArray新的String [] [] {{约翰,玛丽},{爱丽丝,鲍勃}};
的System.out.println(Arrays.toString(deepArray));
//输出:[Ljava.lang.String; @ 106d69c,[Ljava.lang.String; @ 52e922]
的System.out.println(Arrays.deepToString(deepArray));
输出:
[约翰,玛丽],[甲,乙]]
双击
阵列
双击[] =的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]
In Java, arrays don't override toString()
, so if you try to print one directly, you get weird output including the memory location:
int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(intArray); // prints something like '[I@3343c8b3'
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]
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.
Examples:
Simple Array:
String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));
Output:
[John, Mary, Bob]
Nested Array:
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));
Output:
[[John, Mary], [Alice, Bob]]
double
Array:
double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));
Output:
[7.0, 9.0, 5.0, 1.0, 3.0 ]
int
Array:
int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));
Output:
[7, 9, 5, 1, 3 ]
这篇关于什么是打印Java数组最简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!