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

当前回答

通过使用java.util.Arrays:

String mRole = "M_XXX_ABC";        
System.out.println(Arrays.asList(mRole.split("_")).toString());

输出:[M,XXX,ABC]

其他回答

在java8中,这很简单。有两个关键字

stream:数组.stream(intArray).forEach方法引用::printlnint[]intArray=新int[]{1,2,3,4,5};Arrays.stream(intArray).forEach(System.out::println);

如果要在同一行中打印数组中的所有元素,那么只需使用print而不是println,即。

int[] intArray = new int[] {1, 2, 3, 4, 5};
Arrays.stream(intArray).forEach(System.out::print);

另一种没有方法引用的方法只需使用:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(intArray));
// array of primitives:
int[] intArray = new int[] {1, 2, 3, 4, 5};

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

output: [1, 2, 3, 4, 5]

// array of object references:
String[] strArray = new String[] {"John", "Mary", "Bob"};

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

output: [John, Mary, Bob]

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

有以下方法打印阵列

 // 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);
     }

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

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

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

印刷品

abc