🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Thread View: be.comp.programming
1 messages
1 total messages Started by Stino Fri, 07 Nov 2003 20:46
marking a postion in a Java Collection
#3680
Author: Stino
Date: Fri, 07 Nov 2003 20:46
72 lines
3383 bytes
hi all,

I'm trying to do the following in Java.
I have a class that contains an ArrayList.
At certain points in the program I want to mark a position in the ArrayList.

e.g. If I had "A" and "B" then 'mark' and then add "C" and "D"
Then, when I say, 'showFrom()" I should only get to see "C" and "D".
I tried to use an Iterator to do this, but with no succes.
I get the following

Exception in thread "main" java.util.ConcurrentModificationException
         at
java.util.AbstractList$Itr.checkForComodification(AbstractList.java:444)
         at java.util.AbstractList$Itr.next(AbstractList.java:417)
         at IteratorTest.moveIterator(IteratorTest.java:27)
         at IteratorTest.main(IteratorTest.java:41)

The code I tried is the following.

import java.util.*;

public class IteratorTest {
         private ArrayList a;
         private Iterator i;

         public IteratorTest() {
                 a = new ArrayList();
                 i = a.iterator();
         }

         public String toString() {
                 return a.toString();
         }

         public void add(Object o) {
                 a.add(o);
         }

         public void showAll() {
                 Iterator ii = a.iterator();
                 while (ii.hasNext())
                         System.out.print(ii.next() + " ");
         }
         // this should reset the mark
         public void moveIterator() {
                 while (i.hasNext()) i.next();
         }

         public void showFrom() {
                 Iterator ii = i;
                 while (ii.hasNext()) System.out.print(ii.next());
         }

         public static void main(String []args) {
              IteratorTest it = new IteratorTest();
              it.add("A");
              it.add("B");
              it.showAll();
              System.out.println("");
              it.moveIterator();
              it.add("C");
              it.add("D");
              it.showFrom(); // here, I hope to see only C and D
              System.out.println();
         }

}

Thanks for any suggestion on how to solve this problem.

Stino.
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads