Avishka Perera
Avishka Perera

Reputation: 436

java.util.ConcurrentModificationException Can someone explain me the logical reason for this

i am creating a class call student and want to store those on the list i am using iterator to fetch the elements from list but i cant do so because an exception is happening and i cant resolve the exception which is happening here,it would be great help if someone can give me the logical reason for this.Thank you

    import java.awt.List;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.Vector;
    import java.util.List.*;

    public class Runs {

        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub

            try {

                // adding student class to list
                java.util.List list = new ArrayList<Student>();
                Student q = new Student("hello", 1);
                Iterator<Student> l = list.iterator();
                list.add(q);
                // error false in this segment of the code
                Student op = l.next();
                String hhh = op.getnamez();
                System.out.println(hhh);
                System.out.println(op.getnamez());

            } catch (Exception e) {
                System.out.println("" + e);

            }

        }

        public static class Student {
            // student class
            public String name;
            private int age;

            public Student(String s, int a) {

                this.name = s;
                this.age = a;

            }

            public String getnamez() {
                return this.name;

            }

        }

    }

Upvotes: 1

Views: 696

Answers (1)

mhasan
mhasan

Reputation: 3709

Java Collection classes are fail-fast, which means if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException. Concurrent modification exception can come in case of multithreaded as well as single threaded java programming environment.

Here in your example once the line list.add(q); is excuted it changes the modCount attribute of the iterator.

modCount provides the number of times list size has been changed. modCount value is used in every iterator.next() call to check for any modifications in a function checkForComodification().

Hence it finds modCount to be changed it throws ConcurrentModificationException.

So if you want to still do the concurrent modification to your List on which you are running the Iterotir you might need to stick different data structure like CopyOnWriteArrayList in place of List

Upvotes: 3

Related Questions