Why Java Iterator throws ConcurrentModificationException?
When Java Iterator detects the modifications, it cannot guarantee iteration consistency and throws the ConcurrentModificationException.
Java collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:
Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
Implementations, i.e., Classes: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.
Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface.
In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are not collections in the proper use of the term, but they are fully integrated with collections.
When Java Iterator detects the modifications, it cannot guarantee iteration consistency and throws the ConcurrentModificationException.
At entry level Java programmer, you can expect this interview question on Hashtable vs HashMap. Though the question becomes really easy when you know other concepts like how hashmap works, yet after getting a many queries from my blog readers who are preparing for or working at junior level, I …
Learn to design a good custom key class for HashMap. As a rule, always honor the hashcode and equals contract, and make the class immutable.
Using the entrySet() specifically is more powerful and yields better performance than using the keySet() for iteration over a HashMap in Java.
This Java article compares the performance of an ArrayList iteration using simple for-loop, enhanced for-loop, list iterator and stream API.
Learn how hashmap works internally in java with example. Learn the hashmap internal implementation analysis, collision resolution and Java 8 hashmap update.
HowToDoInJava provides tutorials and how-to guides on Java and related technologies.
It also shares the best practices, algorithms & solutions and frequently asked interview questions.