更改java.util.List的输出类型
我创建了这个示例:更改java.util.List的输出类型,java,Java,我创建了这个示例: List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < 10; i++) { list.add(new Random().nextInt(30) + 1); } System.out.println(list); 为什么列表的输出总是用方括号打印数组形状 我的问题是:我可以像这样改变输出的类型吗?13 9 20 3 8 29 13 11 9 16或其他形状?你们可
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 10; i++) {
list.add(new Random().nextInt(30) + 1);
}
System.out.println(list);
为什么列表的输出总是用方括号打印数组形状
我的问题是:我可以像这样改变输出的类型吗?
13 9 20 3 8 29 13 11 9 16或其他形状?你们可以使用正则表达式,但我不是专家
下面是另一种自定义列表输出的方法
创建一个将列表作为参数并输出字符串的方法
public static void main(String[] args) throws java.lang.Exception {
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 10; i++) {
list.add(new Random().nextInt(30) + 1);
}
System.out.println(formatMyList(list));
}
public static String formatMyList(List list){
String str = list.toString().replace("[", "{");
str = str.replace("]", "}");
str = str.replace(",", " -");
return str;
}
您还可以自定义:
public static String formatMyList(List list){
String str = list.toString().replace("[", "I GOT ");
str = str.replace("]", "!");
str = str.replace(",", " AND");
return str;
}
输出:
{25 - 20 - 12 - 25 - 18 - 11 - 17 - 23 - 22 - 29}
I GOT 18 AND 22 AND 14 AND 16 AND 22 AND 21 AND 7 AND 14 AND 21 AND 14!
我会使用
输出:
[13, 9, 20, 3, 8, 29, 13, 11, 9, 16] // array shape
11102991213172819193
list.toString().replaceAll(“\\D+”,”)
包含System.out.println(formatMyList(list))的行由于将列表
传递给原始列表
,因此code>可能会由于类型安全而声明警告。在方法签名中放入通配符以避免出现这种情况。因此,请使用(列表)
而不是(列表)
。
StringBuilder sb = new StringBuilder();
for (int i: list) {
sb.append(i + "\t");
}
System.out.println(sb.toString().trim()); //trim() to remove the last \t