JAVA打印Array数组内容的几种方法

下面是几种常见的打印Array数组内容的方式。

方法一:使用循环打印

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Demo {
public static void main(String[] args) {
String[] infos = new String[] {"Java", "Android", "C/C++", "Kotlin"};

StringBuffer strBuffer = new StringBuffer();
for(int i = 0; i< infos.length; i++) {
if(i > 0) {
strBuffer.append(", ");
}
strBuffer.append(infos[i]);
}
System.out.println(strBuffer);
}
}

方法二:使用 Arrays.toString() 打印

1
2
3
4
5
6
7
public class Demo {
public static void main(String[] args) {
String[] infos = new String[] {"Java", "Android", "C/C++", "Kotlin"};

System.out.println(Arrays.toString(infos));
}
}

方法三:使用 JDK 8 的 java.util.Arrays.stream() 打印

1
2
3
4
5
6
7
public class Demo {
public static void main(String[] args) {
String[] infos = new String[] {"Java", "Android", "C/C++", "Kotlin"};

Arrays.stream(infos).forEach(System.out::println);
}
}

方法四:使用 Arrays.deepToString() 方法打印。如果数组中有其它数组,即多维数组,也会用同样的方法深度显示。

1
2
3
4
5
6
7
public class Demo {
public static void main(String[] args) {
String[] infos = new String[] {"Java", "Android", "C/C++", "Kotlin"};

System.out.println(Arrays.deepToString(infos));
}
}

茴香豆的写法有很多种,打开眼界最重要~

看官可在此打赏