0

could somebody help me to solve my code problem? Error is:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:894)
    at java.util.HashMap$KeyIterator.next(HashMap.java:928)
    at javaTest.Main.main(Main.java:18)

Code is:

public static void main(String arg[]) {
    job.add("a");
    job.add("b");
    HashSet<String> klonasOnJob = job;
    for (String p : klonasOnJob) {
        if (p != "b") {

        } else {
            job.remove(p);
        }
}
Luis
  • 75
  • 6
  • http://stackoverflow.com/questions/1196586/calling-remove-in-foreach-loop-in-java/1196611#1196611 – T.V. Dec 02 '13 at 20:59

1 Answers1

1

Most collections will break and throw ConcurrentModificationException if you modify the collection (in your case by removing an element) while iterating over the collection. Use the iterator's remove() method instead.

In your case the relevant fragment would be:

Iterator<String> it = klonasOnJob.iterator();
while (it.hasNext()) {
    String p = it.next();
    if (p != "b") {

    } else {
        it.remove();
    }
}
Michał Kosmulski
  • 9,855
  • 1
  • 32
  • 51
  • But I'm not modifying the collection while iterating, I create another HashMap and copied it's content to the another. HashSet klonasOnJob = job; job.remove(p); – Luis Dec 04 '13 at 13:50
  • You only set the reference `klonasOnJob` to point to the same object as `job` - this is what assignment does in Java: it just copies the reference and doesn't create a copy of the object like in C++. – Michał Kosmulski Dec 04 '13 at 15:05
  • So basically by removing with this line job.remove(p); I remove from job and klonasOnJob, am I right? – Luis Dec 05 '13 at 14:27
  • Yes - it's just two names that both refer to the same object. – Michał Kosmulski Dec 05 '13 at 15:21