我遇到了很多關於ArrayLists的信息,以及如何操縱它們,但沒有任何東西似乎回答我的問題。使用java中的另一個ArrayList更新ArrayList
我想檢查一個arraylist中的元素是否沒有活動,如果是這樣的話,請將其移除但將另外2個添加到列表中。通常很容易,除非我需要將更改添加到另一個包含第一個數組列表中所有元素以及其他外部數組列表元素的數組列表。
我認爲Id能做到這一點使用一個臨時數組列表如下圖所示:
import java.util.ArrayList;
public class main {
public static ArrayList<String> changedArr = new ArrayList(){ {add("M1"); add("alive"); add("M3");} };
public static ArrayList<String> tempArr = new ArrayList();
public static ArrayList<String> totalArr = new ArrayList(){ {add("M1"); add("alive"); add("M3"); add("L4"); add("S5");} };
public static void main(String[] args) {
System.out.println("changedArray = "+changedArr);
System.out.println("tempArray = "+tempArr);
System.out.println("totalArray = "+totalArr);
for(Object a : changedArr){
if(a !="alive") {
tempArr.clear();
changedArr.remove(a);
totalArr.remove(a);
tempArr.add("S6");
tempArr.add("S7");
changedArr.addAll(tempArr);
totalArr.addAll(tempArr);
}
}
System.out.println("\nchangedArray = "+changedArr);
System.out.println("tempArray = "+tempArr);
System.out.println("totalArray = "+totalArr);
}
}
如果此代碼應返回:
changedArray = [M1, alive, M3]
tempArray = []
totalArray = [M1, alive, M3, L4, S5]
changedArray = [alive, S6, S7]
tempArray = [S6, S7]
totalArray = [alive, L4, S5, S6, S7]
它,而不是返回:
Exception in thread "main" java.util.ConcurrentModificationException
changedArray = [M1, M2, M3]
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
tempArray = []
at java.util.ArrayList$Itr.next(ArrayList.java:851)
totalArray = [M1, M2, M3, L4, S5]
at main.main(main.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Process finished with exit code 1
所以我的問題是,我做錯了什麼導致這些錯誤?這種方法可行嗎?如果沒有,我不明白爲什麼,你能解釋一下嗎?我怎麼能解決它?
如果你已經做到了這一點,感謝您花時間閱讀我的ramblings! :D