遇到同樣的打印代碼,別人的控制台只輸出一行,你的卻重複輸出三行?這通常是因為打印的對象類型不同。
String:System.out.println(str); → 輸出字串內容。List 或集合:System.out.println(list); → 輸出集合的 toString(),格式如 [a, b, c],若集合有三個元素,可能誤以為輸出了三次。確認變數類型,若需逐行輸出集合元素,請遍歷:
for (String s : list) {
System.out.println(s);
}
或使用 Java 8 Stream:list.forEach(System.out::println);
搞清物件類型,避免「以訛傳訛」的輸出誤解。