[英]java arraylist<String> seems to overwrite existing items when using the add() method
我試圖從配置文件中讀取行,並使用add()
方法將每一行附加到ArrayList
。
但是,當我通過使用foreach
打印ArrayList
的內容時,它僅打印要輸入的最后一項。 在我看來,add()方法可能未正確附加? 我也嘗試使用通用的for循環而不是foreach
,結果仍然相同。
public static void interpret(String line){
ArrayList<String> rooms = new ArrayList<>();
ArrayList<String> rules = new ArrayList<>();
// Ignore Room and Rule templates
if(line.contains("(") && line.contains(")")){
System.out.println("skip");
return;
}
if(line.contains("Room;")){
rooms.add(line);
rooms.forEach(System.out::println);
}
if(line.contains("Rule;")){
rules.add(line);
rules.forEach(System.out::println);
}
}
其輸出如下。
Rule; (Room: SmartObject, state{condition}, state{condition}, ...)
skip
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}
它與讀取文件中的實際文本行混合在一起,但是如您所見,它僅在文件上方打印一行,這是最后追加到ArrayList
。
它看起來應該像這樣。
Rule; (Room: SmartObject, state{condition}, state{condition}, ...)
skip
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}
任何幫助/見解將不勝感激。
這是問題所在:
ArrayList<String> rules = new ArrayList<>();
您每次都創建一個新的ArrayList,而不是添加到現有的ArrayList中
建議:
使用以下方法名稱:
public static void interpret(List<String> rooms, List<String> rules, String line){
// Ignore Room and Rule templates
if(line.contains("(") && line.contains(")")){
System.out.println("skip");
return;
}
if(line.contains("Room;")){
rooms.add(line);
rooms.forEach(System.out::println);
}
if(line.contains("Rule;")){
rules.add(line);
rules.forEach(System.out::println);
}
}
與其在每次調用此函數時都創建列表,不如在調用方函數中創建列表並傳遞給此方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.