- How does an Iterator in Java know when to throw ConcurrentModification Exception
- How does an Iterator in Java know when to throw ConcurrentModification Exception
- Iterator in Java
- The Methods Declared by Iterator
- The Methods Declared by ListIterator
- Example
- Output
- Iterators in Java
- What is an Iterator
- How to Import Iterator Class
- How to Get an Iterator
- How to Work with an Iterator
- How to use hasNext() and next() method
- Example
- How to Remove an Item from Collection
- Example
- Conclusion
How does an Iterator in Java know when to throw ConcurrentModification Exception
For collections that implement List, you can also obtain an iterator by calling ListIterator. Conclusion Iterators allow us to traverse through the elements one by one and using iterators different functionalities can be performed like adding or deleting an item.
How does an Iterator in Java know when to throw ConcurrentModification Exception
I have the following code which throws ConcurrentModificationException because I am using two different iterators on the same list and one of them is modifying the list. So, the second iterator throws the exception when reading the list because some other iterator has modified the list.
List list = new ArrayList<>(); populate(list);//A method that adds integers to list ListIterator iterator1 = list.listIterator(); ListIterator iterator2 = list.listIterator(); while (iterator1.hasNext()) < if(iterator1.next() < 5) iterator1.remove(); >while (iterator2.hasNext()) < if(iterator2.next() < 5) < //Call handler >>
My question is how does iterator2 know internally that the list has has been modified by some other iterator if it has not reached an element which is yet removed by iterator1 ? How does it figure out that some other iterator has mutated the list ? One way could be keep track of size but that can’t be the reason since some other iterator can just replace any element.
A good way to answer questions like this is to look at the source code, for example the source code for ArrayList. Search for ConcurrentModificationException .
You should be able to tell that things work rather like this:
- Collection objects have a modification count, which starts at zero and increases whenever an add or remove or similar operation occurs.
- When an iterator object is created, we store the current modification count of the collection inside the iterator.
- Every time the iterator is used, it checks the collection’s mod count against the mod count the iterator got when it was created. If those values differ, the exception is thrown.
In your case, remove operations performed by iterator1 on the list change the structural operation count ( modCount ) of the list. When iterator2 is asked to remove, it sees its expectedModCount , which it received initially as 0, differing from the current mod count of the list.
It should be noted that it.remove is a special case. When an iterator does a remove itself, its expectedModCount adjusts accordingly, to keep in sync with the underlying list.
What is an iterator in Java?, Obtain an iterator to the start of the collection by calling the collection’s iterator ( ) method. Set up a loop that makes a call to hasNext ( ). Have the loop iterate as long as hasNext ( ) returns true. Within the loop, obtain each element by calling next ( ).
Iterator in Java
Often, you will want to cycle through the elements in a collection. For example, you might want to display each element. The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.
Iterator enables you to cycle through a collection, obtaining or removing elements . ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.
Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.
In general, to use an iterator to cycle through the contents of a collection, follow these steps −
- Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method.
- Set up a loop that makes a call to hasnext ( ). Have the loop iterate as long as hasNext( ) returns true.
- Within the loop, obtain each element by calling next( ).
For collections that implement List, you can also obtain an iterator by calling ListIterator.
The Methods Declared by Iterator
Sr.No. | Method & Description |
---|---|
1 | boolean hasNext( ) Returns true if there are more elements. Otherwise, returns false. |
2 | Object next( ) Returns the next element. Throws NoSuchElementException if there is not a next element. |
3 | void remove( ) Removes the current element . Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ). |
The Methods Declared by ListIterator
Sr.No. | Method & Description |
---|---|
1 | void add(Object obj) Inserts obj into the list in front of the element that will be returned by the next call to next( ). |
2 | boolean hasNext( ) Returns true if there is a next element. Otherwise, returns false. |
3 | boolean hasPrevious( ) Returns true if there is a previous element . Otherwise, returns false. |
4 | Object next( ) Returns the next element. A NoSuchElementException is thrown if there is not a next element. |
5 | int nextIndex( ) Returns the index of the next element. If there is not a next element, returns the size of the list. |
6 | Object previous( ) Returns the previous element. A NoSuchElementException is thrown if there is not a previous element. |
7 | int previousIndex( ) Returns the index of the previous element. If there is not a previous element, returns -1. |
8 | void remove( ) Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked. |
9 | void set(Object obj) Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ). |
Example
Here is an example demonstrating both Iterator and ListIterator. It uses an ArrayList object, but the general principles apply to any type of collection.
Of course, ListIterator is available only to those collections that implement the List interface.
import java.util.*; public class IteratorDemo < public static void main(String args[]) < // Create an array list ArrayList al = new ArrayList(); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); // Use iterator to display contents of al System.out.print("Original contents of al: "); Iterator itr = al.iterator(); while(itr.hasNext()) < Object element = itr.next(); System.out.print(element + " "); >System.out.println(); // Modify objects being iterated ListIterator litr = al.listIterator(); while(litr.hasNext()) < Object element = litr.next(); litr.set(element + "+"); >System.out.print("Modified contents of al: "); itr = al.iterator(); while(itr.hasNext()) < Object element = itr.next(); System.out.print(element + " "); >System.out.println(); // Now, display the list backwards System.out.print("Modified list backwards: "); while(litr.hasPrevious()) < Object element = litr.previous(); System.out.print(element + " "); >System.out.println(); > >
This will produce the following result −
Output
Original contents of al: C A E B D F Modified contents of al: C+ A+ E+ B+ D+ F+ Modified list backwards: F+ D+ B+ E+ A+ C+
ListIterator in Java, It is a java iterator that is used to traverse all types of lists including ArrayList, Vector, LinkedList, Stack, etc. It is available since Java 1.2. It extends the iterator interface. The hierarchy of ListIterator is as follows: Some Important points about ListIterator It is useful for list implemented classes. Available since java 1.2.
Iterators in Java
In Java, the concept of Collection is most frequently used which is nothing but a group of elements. To traverse each item of a collection, java iterators are used. As java is an object-oriented programming language, it allows us to store the data dynamically therefore to traverse the dynamically stored items we can utilize the java iterators .
This write-up provides a thorough overview of Iterator in java and in this regard it covers the following concepts:
- What is an Iterator
- How to Import Iterator Class
- How to work with an Iterator
- How to get Iterator
- Iterating Through a Collection using hasNext() and next() methods
- How to use remove() method
What is an Iterator
The concept of an iterator can be used to traverse the items that are stored dynamically. It can be used to traverse the collection classes like ArrayList and LinkedList.
How to Import Iterator Class
We have to follow a couple of steps to avail the functionalities of an iterator:
In the first step, we need to import the Iterator class of java.util package:
How to Get an Iterator
To get an iterator for a collection, all we need to do is use the iterator() method with any collection such as ArrayList, LinkedList:
In the above-given snippet, we assume that “ arrayListObject ” is an object of collection that belongs to the ArrayList class.
How to Work with an Iterator
Multiple methods are available to work with iterators as listed below:
We will discuss each of the above-mentioned methods in detail.
How to use hasNext() and next() method
In order to traverse through a collection the hasNext() method can be used. The hastNext() checks if there are some more items left in the iteration; if yes then it will return true; otherwise it will return false. While the next() method will return the next item in the traversal and it would throw an exception if there are no more elements left.
Example
In this example, first we create a collection of an ArrayList, then we get the iterator from the ArrayList to traverse the items. And finally we iterate through the collection using hasNext() and next() method:
public class IteratorsExample <
public static void main ( String [ ] args ) <
ArrayList < String >subjects = new ArrayList <> ( ) ;
subjects. add ( «Computer Science» ) ;
subjects. add ( «Mathematics» ) ;
subjects. add ( «Chemistry» ) ;
subjects. add ( «Biology» ) ;
subjects. add ( «Physics» ) ;
Iterator < String >iterate = subjects. iterator ( ) ;
while ( iterate. hasNext ( ) ) <
System . out . println ( iterate. next ( ) ) ;
>
>
>
In the above-snippet, within while loop condition, we utilize hasNext() method to check if there is an item left in the collection, if yes then loop will execute and within the body of loop, the next() method will return the next item in the traversal that will be display with the help of System.out.println():
The output verified the working of iterators.
How to Remove an Item from Collection
The remove() method can be used to delete a value from the Iterator.
Example
In this example we will utilize the remove method to remove the item “Biology”.
String st ;
while ( iterate. hasNext ( ) ) <
st = ( String ) iterate. next ( ) ;
if ( st. equals ( «Biology» ) ) <
iterate. remove ( ) ;
System . out . println ( «Biology removed» ) ;
break ;
>
In the above code snippet, we specified a condition st.equals(“Biology”) and with the body of the if statement, we utilized the remove() method. It describes that test if the string value is “Biology”, then remove it from the collection:
Output authenticates the working of the remove method as it successfully removes the item from the collection.
Conclusion
Iterators allow us to traverse through the elements one by one and using iterators different functionalities can be performed like adding or deleting an item. In order to traverse through a collection multiple methods can be used such as hasNext() to test if there are some more items left in the iteration or not, the next() method to return the next item in the traversal, and remove() method to remove any specific element of the collection. This write-up provides a comprehensive guide for the Iterators In Java .
How to Remove an Element from Collection using, Approach 1: Using Iterator. A List is created and elements are added to the list using the add () method. The Iterator object is used to iterate over the elements of the list using the hasNext () and next () methods. An if the condition is used within the while loop and when the condition is satisfied, the particular …