Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

java - 打印Java数组的最简单方法是什么?(What's the simplest way to print a Java array?)

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() :

(在Java中,数组不会覆盖toString() ,因此,如果尝试直接打印一个,则将得到className +'@'+数组的hashCode的十六进制,如Object.toString()所定义:)

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

(但是通常,我们实际上想要的是更多类似[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]
  ask by Alex Spurling translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays.

(从Java 5开始,您可以将Arrays.toString(arr)Arrays.deepToString(arr)用于数组中的数组。)

Note that the Object[] version calls .toString() on each object in the array.

(请注意, Object[]版本在数组中的每个对象上调用.toString() 。)

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数组:)

     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数组:)

     int[] intArray = { 7, 9, 5, 1, 3 }; System.out.println(Arrays.toString(intArray)); 

    Output:

    (输出:)

     [7, 9, 5, 1, 3 ] 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...