Dynamic Collection Iterator for Java
Introduction
A very simple java iterator used to go over a collection that can change during the iteration
About Dynamic Collection Iterator
Items returned by the dynamic collection iterator are items which:
- Exist in the collection during the iterator creation
- AND were not remove from the collection during the iteration
Use it to aviod java.util.ConcurrentModificationException thrown during iteration of modified collection
Source Code
import
java.util.*;
|
Requirements
- Java Platform, Standard Edition
Usage
Using the Dynamic Collection Iterator is easy:
- Create the iterator, and send the collection you want to iterate
- Start the iteration
- Note: for better performance the underlying collection better be a Set because the dynamic list iteraror uses the contains method
Example
public static
void
main
(
String args
[]) {
Collection<Integer> collection =
new
LinkedList<Integer>
()
;
collection.add
(
1
)
;
collection.add
(
2
)
;
collection.add
(
3
)
;
Iterator<Integer> iterator =
new
DynamicCollectionIterator<Integer>
(
collection
)
;
System.out.println
(
iterator.hasNext
())
;
// true
System.out.println
(
iterator.next
())
;
// 1
collection.remove
(
3
)
;
collection.add
(
4
)
;
System.out.println
(
iterator.hasNext
())
;
// true
System.out.println
(
iterator.next
())
;
// 2
System.out.println
(
iterator.hasNext
())
;
// false
}
Help and Support
For questions and suggestions please contant support@small-software.com