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

当前回答

如果使用Commons.Lang库,我们可以做到:

ArrayUtils.toString(数组)

int[] intArray = new int[] {1, 2, 3, 4, 5};
String[] strArray = new String[] {"John", "Mary", "Bob"};
ArrayUtils.toString(intArray);
ArrayUtils.toString(strArray);

输出:

{1,2,3,4,5}
{John,Mary,Bob}

其他回答

阵列.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 1.4,您可以改为:

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

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

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

此外,您还可以使用:

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

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

不过,很高兴知道,关于“总是先检查标准库”,我从来不会偶然发现Arrays.toString(myarray)的技巧

--因为我正专注于myarray的类型,看看如何做到这一点。我不想重复这个过程:我想要一个简单的调用,让它看起来像我在Eclipse调试器中看到的那样,而myarray.toString()并没有这么做。

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );
public class printer {

    public static void main(String[] args) {
        String a[] = new String[4];
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the data");
        for (int i = 0; i < 4; i++) {
            a[i] = sc.nextLine();
        }
        System.out.println("the entered data is");
        for (String i : a) {
            System.out.println(i);
        }
      }
    }