我创建了这个示例:
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] // array shape
为什么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;
}
输出:
{25 - 20 - 12 - 25 - 18 - 11 - 17 - 23 - 22 - 29}
<小时/>
您还可以自定义:
public static String formatMyList(List list){
String str = list.toString().replace("[", "I GOT ");
str = str.replace("]", "!");
str = str.replace(",", " AND");
return str;
}
输出:
I GOT 18 AND 22 AND 14 AND 16 AND 22 AND 21 AND 7 AND 14 AND 21 AND 14!
关于java - 更改 java.util.List 的输出类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33193737/