[英]How I can add objects into an ArrayList when I'm using this ArrayList in a for loop?
我需要將一些對象添加到我在for循環中使用的ArrayList中。 這是代碼:
List<Bulto> bultosHijos = bultoDAO.findChilds(idBulto);
List<Bulto> bultosMasProfundos = new ArrayList();
for (Bulto bulto : bultosHijos) {
List<Bulto> bultosNietos = bultoDAO.findChilds(bulto.getIdBulto());
if (!bultosNietos.isEmpty()) {
bultosHijos.addAll(bultosHijos.size(), bultosNietos);
} else {
bultosMasProfundos.add(bulto);
}
}
這使我拋出“當前修改異常”。 我嘗試更改返回DAO的類型,但我做不到。 如何避免此錯誤並執行此操作?
非常感謝
編輯1:
感謝您的回復! 我現在使用ListIterator並與下面的代碼一起使用,效果很好! 但是,如果我不使用listIterator.previous()
,則while循環立即退出,我不希望這樣做。 可以嗎
List<Bulto> bultosHijos = bultoDAO.findChilds(idBulto);
List<Bulto> bultosMasProfundos = new ArrayList();
ListIterator<Bulto> listIterator = bultosHijos.listIterator();
while (listIterator.hasNext()) {
Bulto bulto = listIterator.next();
List<Bulto> bultosNietos = bultoDAO.findChilds(bulto.getIdBulto());
if (!bultosNietos.isEmpty()) {
for (Bulto bultoNieto : bultosNietos) {
listIterator.add(bultoNieto);
listIterator.previous();
}
} else {
bultosMasProfundos.add(bulto);
}
}
使用的ListIterator添加或在迭代ArrayList的同時去除。 當您嘗試使用forloop從列表中添加或刪除對象時,它肯定會引發Current Modification Exception
。 因此,您無法修改列表。 通過使用ListIterator
您可以從列表中add remove
對象。
這是示例代碼:
List<String> list1=new ArrayList<String>();
list1.add("a");
list1.add("b");
// c is missing in the list
list1.add("d");
list1.add("e");
ListIterator<String> it=list1.listIterator();
while(it.hasNext()){
if(it.next().equals("b")){
// add c in the list after b
it.add("c");
}
}
System.out.println(Arrays.toString(list1.toArray(new String[]{})));
輸出:
[a, b, c, d, e]
在循環訪問ArrayList時,如果要對其進行任何修改,則必須通過迭代器循環,因為常規的for循環對您沒有幫助,請看這里 。
Iterator<String> iter = myArrayList.iterator();
while (iter.hasNext()) {
String str = iter.next();
if (someCondition)
iter.remove();
}
循環訪問時,被允許添加到ArrayList
的唯一方法是使用迭代器:
ListIterator<String> iterator = bultosHijos.iterator();
while (iterator.hasNext()) {
String str = iterator.next();
// now if we want to...
iterator.add("some other string");
}
迭代器還具有.remove()
和.set()
用於編輯元素。
沒有.addAll()
上ListIterator
,因此,如果您要添加大量的元素,你必須創建自己的循環,並通過一個將它們添加一個:
for (String s: bultosNietos)
iterator.add(s);
修改列表的任何其他方法都會給出ConcurrentModificationException
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.