Thursday, May 15, 2008

Java Iterator

Iterator also has a method remove( ) , when its called it will remove from source the last item retrieved from next( )

If remove is called twice in succesion without a call to next in between IllegalStateException is thrown can get Concurrent MOdification exceptiion if someone else is modifying the collection

according to http://java.sun.com/j2se/1.4.2/docs/api/java/util/Iterator.html#remove()
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.


import java.util.*;
public class DelMeCollection {
public static List l = new ArrayList(25);
static class ListIterateThread extends Thread {
public void run( ){
System.out.println("thread started ");
Iterator listItr = l.iterator();
System.out.println("got the iterator ");
try {
while(listItr.hasNext())
System.out.println("val is "+listItr.next());
} catch(Exception e ) {
System.out.println("some exception "+e);
// wonder why no concurrent modification exception
}
}
}

public static void main(String[] args) {
System.out.println("inside main THREAD");
ListIterateThread lt= new ListIterateThread();
List l = new ArrayList(25);
lt.start();
l.add("1"); System.out.println("added 1");
l.add("2"); System.out.println("added 2");
l.add("3"); System.out.println("added 3");
l.add("4"); System.out.println("added 4");
l.add("5"); System.out.println("added 5");


l.add("11"); System.out.println("added 11");
l.add("12"); System.out.println("added 12");
l.add("13"); System.out.println("added 13");
l.add("14"); System.out.println("added 14");
l.add("15"); System.out.println("added 15");

try {
Thread.currentThread().sleep(5);
} catch (InterruptedException e) {
System.out.println("exception "+e);
}

l.add("21"); System.out.println("added 21");
l.add("22"); System.out.println("added 22");
l.add("23"); System.out.println("added 23");
l.add("24"); System.out.println("added 24");
l.add("25"); System.out.println("added 25");

l.add("31"); System.out.println("added 31");
l.add("32"); System.out.println("added 32");
l.add("33"); System.out.println("added 33");
l.add("34"); System.out.println("added 34");
l.add("35"); System.out.println("added 35");

}
}


Got Output


inside main THREAD
added 1
added 2
added 3
added 4
thread started
added 5
got the iterator
added 11
added 12
added 13
added 14
added 15
added 21
added 22
added 23
added 24
added 25
added 31
added 32
added 33
added 34
added 35


If you want to iterate through "Filtered Collection" try this

No comments: