简介
在 Java 中,字符串数组列表是一个存储字符串数组的集合。有几种方法可以打印字符串数组列表。
使用 System.out.println()
System.out.println()
方法可以打印任何类型的值,包括字符串数组列表。
示例:
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<String[]> list = new ArrayList<>();
list.add(new String[] {
"John", "Smith"});
list.add(new String[] {
"Mary", "Johnson"});
list.add(new String[] {
"Bob", "Brown"});
// 遍历列表并打印每个字符串数组
for (String[] arr : list) {
System.out.println(arr[0] + " " + arr[1]);
}
}
}
输出:
John Smith
Mary Johnson
Bob Brown
使用 toString()
方法
每个 Java 对象都有一个 toString()
方法,它返回对象的字符串表示形式。对于字符串数组列表,toString()
方法返回一个字符串,其中包含每个字符串数组的元素,用逗号分隔。
示例:
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<String[]> list = new ArrayList<>();
list.add(new String[] {
"John", "Smith"});
list.add(new String[] {
"Mary", "Johnson"});
list.add(new String[] {
"Bob", "Brown"});
// 打印列表的字符串表示形式
System.out.println(list.toString());
}
}
输出:
[[John, Smith], [Mary, Johnson], [Bob, Brown]]
使用 Arrays.deepToString()
方法
Arrays.deepToString()
方法可以打印多维数组的字符串表示形式。它可以用来打印字符串数组列表,因为它本质上是一个多维数组。
示例:
import java.util.ArrayList;
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
ArrayList<String[]> list = new ArrayList<>();
list.add(new String[] {
"John", "Smith"});
list.add(new String[] {
"Mary", "Johnson"});
list.add(new String[] {
"Bob", "Brown"});
// 打印列表的深度字符串表示形式
System.out.println(Arrays.deepToString(list.toArray()));
}
}
输出:
[[John, Smith], [Mary, Johnson], [Bob, Brown]]
总结
有几种方法可以在 Java 中打印字符串数组列表:
- 使用
System.out.println()
方法遍历列表并打印每个字符串数组。 - 使用
toString()
方法打印列表的字符串表示形式。 - 使用
Arrays.deepToString()
方法打印列表的深度字符串表示形式。
选择哪种方法取决于所需的输出格式和代码简洁性。