打印 Java 数组的最简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/409784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:17:34  来源:igfitidea点击:

What's the simplest way to print a Java array?

javaarraysprinting

提问by Alex Spurling

In Java, arrays don't override toString(), so if you try to print one directly, you get the className+ '@' + the hex of the hashCodeof 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]. What's the simplest way of doing that? Here are some example inputs and outputs:

但通常,我们实际上想要更像[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]

采纳答案by Esko

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.

从 Java 5 开始,您可以在数组中使用Arrays.toString(arr)Arrays.deepToString(arr)数组。请注意,Object[]版本调用.toString()数组中的每个对象。输出甚至以您要求的确切方式进行装饰。

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]]
    
  • doubleArray:

    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 ]
    
  • intArray:

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

    Output:

    [7, 9, 5, 1, 3 ]
    
  • 简单数组:

    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 ]
    

回答by Limbic System

Always check the standard libraries first.

总是先检查标准库。

import java.util.Arrays;

Then try:

然后尝试:

System.out.println(Arrays.toString(array));

or if your array contains other arrays as elements:

或者如果您的数组包含其他数组作为元素:

System.out.println(Arrays.deepToString(array));

回答by Ross

If you're using Java 1.4, you can instead do:

如果您使用的是 Java 1.4,则可以改为:

System.out.println(Arrays.asList(array));

(This works in 1.5+ too, of course.)

(当然,这也适用于 1.5+。)

回答by Russ Bateman

This is nice to know, however, as for "always check the standard libraries first" I'd never have stumbled upon the trick of Arrays.toString( myarray )

很高兴知道,但是,至于“始终首先检查标准库”,我从来没有偶然发现 Arrays.toString( myarray )

--since I was concentrating on the type of myarray to see how to do this. I didn't want to have to iterate through the thing: I wanted an easy call to make it come out similar to what I see in the Eclipse debugger and myarray.toString() just wasn't doing it.

--因为我专注于 myarray 的类型以了解如何执行此操作。我不想遍历整个事情:我想要一个简单的调用,使它与我在 Eclipse 调试器中看到的相似,而 myarray.toString() 只是没有这样做。

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );

回答by somedude

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

回答by Rhyous

Arrays.deepToString(arr)only prints on one line.

Arrays.deepToString(arr)只打印在一行上。

int[][] table = new int[2][2];

To actually get a table to print as a two dimensional table, I had to do this:

要真正将表格打印为二维表格,我必须这样做:

System.out.println(Arrays.deepToString(table).replaceAll("],", "]," + System.getProperty("line.separator")));

It seems like the Arrays.deepToString(arr)method should take a separator string, but unfortunately it doesn't.

Arrays.deepToString(arr)方法似乎应该采用分隔符字符串,但不幸的是它没有。

回答by Andrew_Dublin

Using regular forloop is the simplest way of printing array in my opinion. Here you have a sample code based on your intArray

在我看来,使用常规for循环是打印数组的最简单方法。这里有一个基于 intArray 的示例代码

for (int i = 0; i < intArray.length; i++) {
   System.out.print(intArray[i] + ", ");
}

It gives output as yours 1, 2, 3, 4, 5

它给你的输出 1, 2, 3, 4, 5

回答by Eric Baker

In JDK1.8 you can use aggregate operations and a lambda expression:

在 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
*/

回答by Jean Logeart

To add to all the answers, printing the object as a JSON string is also an option.

要添加到所有答案中,将对象打印为 JSON 字符串也是一种选择。

Using Hymanson:

使用Hyman逊:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(anyArray));

Using Gson:

使用 Gson:

Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));

回答by Roam

There's one additional way if your array is of type char[]:

如果您的数组是 char[] 类型,还有一种方法:

char A[] = {'a', 'b', 'c'}; 

System.out.println(A); // no other arguments

prints

印刷

abc