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

当前回答

如果您正在运行jdk 8。

public static void print(int[] array) {
    StringJoiner joiner = new StringJoiner(",", "[", "]");
    Arrays.stream(array).forEach(element -> joiner.add(element + ""));
    System.out.println(joiner.toString());
}


int[] array = new int[]{7, 3, 5, 1, 3};
print(array);

输出:

[7,3,5,1,3]

其他回答

我最近在Vanilla#Java上看到了这篇文章。编写Arrays.toString(arr);,然后导入java.util.Arrays;总是

请注意,无论如何,这不是永久性的修复。只是一个可以使调试更简单的黑客。

打印一个数组直接给出内部表示和hashCode。现在,所有类都将Object作为父类型。那么,为什么不破解Object.toString()呢?如果不进行修改,Object类如下所示:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

如果更改为:

public String toString() {
    if (this instanceof boolean[])
        return Arrays.toString((boolean[]) this);
    if (this instanceof byte[])
        return Arrays.toString((byte[]) this);
    if (this instanceof short[])
        return Arrays.toString((short[]) this);
    if (this instanceof char[])
        return Arrays.toString((char[]) this);
    if (this instanceof int[])
        return Arrays.toString((int[]) this);
    if (this instanceof long[])
        return Arrays.toString((long[]) this);
    if (this instanceof float[])
        return Arrays.toString((float[]) this);
    if (this instanceof double[])
        return Arrays.toString((double[]) this);
    if (this instanceof Object[])
        return Arrays.deepToString((Object[]) this);
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

通过向命令行添加以下内容,可以简单地将这个修改后的类添加到类路径中:-Xbootclasspath/p:target/classes。

现在,随着自Java5以来deepToString(..)的可用性,toString(.)可以很容易地更改为deepToString(..),以添加对包含其他数组的数组的支持。

我发现这是一个非常有用的黑客,如果Java可以简单地添加它,那就太好了。我理解拥有非常大的数组可能存在的问题,因为字符串表示可能会有问题。可能会传递类似System.out或PrintWriter这样的事件。

toString是一种将数组转换为字符串的方法。

此外,您还可以使用:

for (int i = 0; i < myArray.length; i++){
System.out.println(myArray[i] + " ");
}

此for循环将使您能够按顺序打印数组的每个值。

从Java 8开始,还可以利用String类提供的join()方法打印出数组元素,不带括号,并用分隔符分隔(这是下面示例中的空格字符):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

输出将是“嘿,朋友!”。

阵列.to字符串

作为一个直接的答案,包括@Esko在内的几个公司使用Arrays.toString和Arrays.deepToString方法提供的解决方案是最好的。

Java 8-Stream.collect(joining()),Stream.forEach

下面,我尝试列出一些建议的其他方法,试图进行一些改进,其中最值得注意的是使用Stream.collect运算符,使用一个加入的收集器来模拟String.join正在做的事情。

int[] ints = new int[] {1, 2, 3, 4, 5};
System.out.println(IntStream.of(ints).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
System.out.println(IntStream.of(ints).boxed().map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(ints));

String[] strs = new String[] {"John", "Mary", "Bob"};
System.out.println(Stream.of(strs).collect(Collectors.joining(", ")));
System.out.println(String.join(", ", strs));
System.out.println(Arrays.toString(strs));

DayOfWeek [] days = { FRIDAY, MONDAY, TUESDAY };
System.out.println(Stream.of(days).map(Object::toString).collect(Collectors.joining(", ")));
System.out.println(Arrays.toString(days));

// These options are not the same as each item is printed on a new line:
IntStream.of(ints).forEach(System.out::println);
Stream.of(strs).forEach(System.out::println);
Stream.of(days).forEach(System.out::println);

如果您使用的是Java 11

import java.util.Arrays;
public class HelloWorld{

     public static void main(String []args){
        String[] array = { "John", "Mahta", "Sara" };
       System.out.println(Arrays.toString(array).replace(",", "").replace("[", "").replace("]", ""));
     }
}

输出:

John Mahta Sara