Results 1 to 3 of 3

Thread: Iterator

  1. #1
    Dayanand is offline Member
    Join Date
    Feb 2011
    Posts
    61
    Rep Power
    0

    Default Iterator

    package iterators;

    import java.util.ArrayList;
    import java.util.Iterator;

    public class Mgr
    {
    public static void main(String[] args)
    {
    ArrayList list = new ArrayList();
    list.add(90);
    list.add(12);
    list.add(99);
    list.add(34);
    list.add(23);
    list.add(56);

    Iterator iterator = list.iterator();
    Iterator iterator2 = list.iterator();

    while (iterator.hasNext())
    {
    System.out.println(iterator.next());
    Object object = (Object) iterator.next();
    System.out.println((Integer)object);
    }
    System.out.println("<--------------------------->");
    iterator.remove();
    list.add((Object)(String)"Daya");
    list.add((Object)(Integer)143);
    list.add((Object)(String)("shwetha"));
    System.out.println(list);

    while (iterator2.hasNext())
    {
    Object object = (Object) iterator2.next();
    System.out.println(object);

    }

    System.out.println(iterator.equals(iterator2));;
    }
    }
    Hi
    here i am iterating list for second time with different object(i.e iterator2)
    but i got java.util.ConcurrentModificationException,how its possbile..................is there any concept over here

    Thanks in advance
    Daya

  2. #2
    Leanne182x is offline Member
    Join Date
    Feb 2011
    Posts
    3
    Rep Power
    0

    Default

    If you move the line

    Iterator iterator2 = list.iterator();

    to be after you edit the list with iterator ( so after list.add((Object)(String)("shwetha")); )
    then it seems to work. I'm no advanced Java user myself but I think it's because you create iterator2 with the elements in the list and then modify that list with the first iterator which throws the exception when trying to iterate those objects with iterator2.

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,085
    Rep Power
    20

    Default

    That's exactly it.
    Both iterators are created.
    Then one iterator changes the underlying list.
    The attempt to access the second iterator results in it seeing that the list has changed, so the exception is thrown.

Similar Threads

  1. for..iterator
    By jon80 in forum New To Java
    Replies: 2
    Last Post: 11-28-2010, 02:12 PM
  2. Replies: 0
    Last Post: 05-18-2010, 12:53 AM
  3. Iterator help
    By alpdog14 in forum New To Java
    Replies: 2
    Last Post: 10-13-2009, 08:42 PM
  4. iterator
    By venkatallu in forum Advanced Java
    Replies: 3
    Last Post: 09-23-2008, 01:32 PM
  5. Iterator
    By eva in forum New To Java
    Replies: 0
    Last Post: 01-31-2008, 02:07 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •