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:

  1. Exist in the collection during the iterator creation
  2. 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.*;

/**
* Used to iterate a collection that can change during iteration.
*
* 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
*
*/
public class DynamicCollectionIterator<T> implements Iterator<T> {

   
private final Collection<T> collection;
   
private final Iterator<T> copyIterator;
   
private T nextItem;

   
public DynamicCollectionIterator ( Collection<T> collection ) {
       
this .collection = collection;
        Collection<T> collectionCopy =
new ArrayList<T> ( collection ) ;
       
this .copyIterator = collectionCopy.iterator () ;
       
this .nextItem = null ;
   
}

   
public boolean hasNext () {
       
while ( copyIterator.hasNext ()) {
           
T item = copyIterator.next () ;
           
if ( collection.contains ( item )) {
               
this .nextItem = item;
               
return true ;
           
}
        }
       
return false ;
   
}

   
public T next () {
       
if ( nextItem == null )
           
if ( !hasNext ())
               
return null ;
       
try {
           
return nextItem;
       
}
       
finally {
           
this .nextItem = null ;
       
}
    }

   
public void remove () {
       
throw new UnsupportedOperationException () ;
   
}
}

Requirements

  1. Java Platform, Standard Edition

Usage

Using the Dynamic Collection Iterator is easy:

  1. Create the iterator, and send the collection you want to iterate
  2. Start the iteration
  3. 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

Ads