1. 输出内容最常见的方式
[java]
// List<String>类型的列表
List<String> list = new ArrayList<String>();
list.add("First");
list.add("Second");
list.add("Third");
list.add("Fourth");
System.out.println(list);
输出:
[First, Second, Third, Fourth]
[java]
// String数组
<pre name="code" class="java">String[] array = new String[] { "First", "Second", "Third", "Fourth" };
System.out.println(array.toString());
输出:
[Ljava.lang.String;@12dacd1
2. 使用Array类输出数组内容
[java]
// String数组
String[] array = new String[] { "First", "Second", "Third", "Fourth" };
System.out.println(Arrays.toString(array));
输出:
[First, Second, Third, Fourth]
3. 输出数组的数组
可以使用Arrays.deepToString()方法。
[java]
String[] arr1 = new String[] { "Fifth", "Sixth" };
String[] arr2 = new String[] { "Seventh", "Eight" };
// 数组的数组
String[][] arrayOfArray = new String[][] { arr1, arr2 };
// 比较下面的输出
System.out.println(arrayOfArray);
System.out.println(Arrays.toString(arrayOfArray));
System.out.println(Arrays.deepToString(arrayOfArray));
输出:
[[Ljava.lang.String;@1ad086a
[[Ljava.lang.String;@10385c1, [Ljava.lang.String;@42719c]
[[Fifth, Sixth], [Seventh, Eighth]]
再看下面的完整例子:
[java]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PrintArray {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("First");
list.add("Second");
list.add("Third");
list.add("Fourth");
System.out.println(list);
String[] array = new String[] { "First", "Second", "Third", "Fourth" };
System.out.println(array.toString());
System.out.println(Arrays.toString(array));
String[] arr1 = new String[] { "Fifth", "Sixth" };
String[] arr2 = new String[] { "Seventh", "Eigth" };
String[][] arrayOfArray = new String[][] { arr1, arr2 };
System.out.println(arrayOfArray);
System.out.println(Arrays.toString(arrayOfArray));
System.out.println(Arrays.deepToString(arrayOfArray));
}
}
输出:
[First, Second, Third, Fourth]
[Ljava.lang.String;@12dacd1
[First, Second, Third, Fourth]
[[Ljava.lang.String;@1ad086a
[[Ljava.lang.String;@10385c1, [Ljava.lang.String;@42719c]
[[Fifth, Sixth], [Seventh, Eigth]]
转载于:https://blog.51cto.com/jaiaiifh/1091303