在Java中,数组不会重写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]的东西。最简单的方法是什么?以下是一些输入和输出示例:

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

当前回答

要添加到所有答案中,还可以选择将对象打印为JSON字符串。

使用Jackson:

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

使用Gson:

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

其他回答

无论您使用哪个JDK版本,它都应始终有效:

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

如果数组包含对象,则该方法将起作用。如果数组包含基元类型,则可以使用包装器类,而不是将基元直接存储为。。

例子:

int[] a = new int[]{1,2,3,4,5};

替换为:

Integer[] a = new Integer[]{1,2,3,4,5};

更新:

对需要指出的是,将数组转换为对象数组OR以使用object的数组是昂贵的。这是由于java的特性,称为自动装箱。

因此,仅用于打印目的,不应使用。我们可以创建一个函数,该函数将数组作为参数,并将所需格式打印为

public void printArray(int [] a){
        //write printing code
} 

我尝试过的一个简化快捷方式是:

    int x[] = {1,2,3};
    String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
    System.out.println(printableText);

它将打印

1
2
3

这种方法不需要循环,最好只用于小型阵列

有以下方法打印阵列

 // 1) toString()  
    int[] arrayInt = new int[] {10, 20, 30, 40, 50};  
    System.out.println(Arrays.toString(arrayInt));

// 2 for loop()
    for (int number : arrayInt) {
        System.out.println(number);
    }

// 3 for each()
    for(int x: arrayInt){
         System.out.println(x);
     }
for(int n: someArray) {
    System.out.println(n+" ");
}

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