Java iterator

Algorithmus, Baumdurchlauf, Compiler, Interpreter...; Cobol, Pascal, C/C++, Java & Co.
Antworten
Benutzeravatar
stag3k
Forums-Profi
Forums-Profi
Beiträge: 178
Registriert: 21.01.09 18:02
Wohnort: Hamburg

Hallo liebe Freunde der gepflegten Java-Unterhaltung,

warum erhalte ich bei diesem Code

import java.util.ArrayList;
import java.util.Iterator;

public class ArtikelArray {

public static void main(String[] args) {

ArrayList <String> artikel = new ArrayList <String>();
/*String a = null;*/
Iterator <String> iterator = artikel.iterator();

artikel.add("Uhr");
artikel.add("Tasche");
artikel.add("Laptop");
artikel.add("Koffer");
artikel.add("Jacke");

System.out.println(artikel.isEmpty());
System.out.println("\n");

for (int i=0; i<artikel.size(); i++)
System.out.println(artikel.get(i));
System.out.println("\n");

while(iterator.hasNext())
{
System.out.println(iterator.next());
}

artikel.remove("Koffer");
for (int i=0; i<artikel.size(); i++)
System.out.println(artikel.get(i));
System.out.println("\n");

artikel.set(1, "Koffer");
for (int i=0; i<artikel.size(); i++)
System.out.println(artikel.get(i));
System.out.println("\n");

artikel.add(1, "Tasche");
for (int i=0; i<artikel.size(); i++)
System.out.println(artikel.get(i));
System.out.println("\n");

}

}
folgende Exception?
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at ArtikelArray.main(ArtikelArray.java:28)
Kann mir bitte einer der Gurus weiterhelfen? :)

Danke!
ragn
Mitglied
Mitglied
Beiträge: 24
Registriert: 30.03.11 11:43

Das Problem ist das du den Iterator erzeugst und im folgenden erst die einzelnen Elemente hinzufügst.
Wenn du "Iterator <String> iterator = artikel.iterator();" direkt vor die Schleife in Zeile 26 setzt funktioniert es einwandfrei.

Definitv sagen woran es liegt kann ich dir adhoc leider nicht, ich vermute aber das der Iterator intern die Länge/Status der ArrayList hält.
Durch das folgende hinzufügen sind die Werte dann nicht mehr konsistent und es kommt ab einem bestimmten Element zu dieser Exception.

Gruß

Ralf

P.S.: Bin grad noch auf die Lösung in der Java Dokumentation gestoßen. Meine Vermutung bestätigt das...

http://java.sun.com/j2se/1.4.2/docs/api ... yList.html
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Benutzeravatar
stag3k
Forums-Profi
Forums-Profi
Beiträge: 178
Registriert: 21.01.09 18:02
Wohnort: Hamburg

es läuft!

ich bin begeistert, danke! :)
Antworten