Java collection to add and remove on repeat

I am wondering if there is any environment that implements a collection that will have the following behavior.


Suppose that it initially contains: [1, 2, 3]

  • I repeat it (using an iterator) and reaching element 2, now I add 4 to the end (now the collection will be [1, 2, 3, 4]).
  • I now create a new iterator and iterate over the collection, resulting in [1, 2, 3, 4]
  • I continue the iteration with the first iterator and it will give me only 3 and return
  • now resetting the first iterator will give me [1, 2, 3, 4] (similar to creating a new one).

The same should apply for deleting items. If I remove 3 instead of adding, the second iterator should give me [1, 2], while the first one will still give me 3 and the end.


So when I receive and iterator, I want it to give me the collection that I had when I created the iterator (even if I repeat it later, I will go over a bit and continue later), when I reset the iterator, it gets garbage collection , it is updated to the latest versions, and I have to have several iterator instances created at different times, which will give different versions depending on the contents of the array when creating the iterator.

I need it to work well with multiple threads, and it is preferable to have an efficient implementation.

Does anyone know about any implementation of such a collection, or should I implement it myself?

+5
source share
5 answers

What you are describing is very similar to how it works CopyOnWriteArrayList:

  • ( ),
  • ,

:

1 - 1
4
2 - 1
2 - 2
2 - 3
2 - 4
1 - 2
1 - 3

public static void main(String[] args) throws InterruptedException {
    final List<Integer> list = new CopyOnWriteArrayList<Integer>();
    list.addAll(Arrays.asList(1, 2, 3));
    new Thread(new Runnable() {

        @Override
        public void run() {
            for (Integer i : list) {
                System.out.println("Iterator 1 - " + i);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {}
            }
        }
    }).start();
    Thread.sleep(10);
    list.add(4);
    System.out.println("4 has been added");
    for (Integer i : list) {
        System.out.println("Iterator 2 - " + i);
    }

}
+6

java.util.concurrent.CopyOnWriteArrayList<E>

:

ArrayList, (, ..) .

, .

, , , , , , . "" , .

, (remove, set add) Iterator .

+3

ImmutableCollections guava.

The returned ImmutableList is often - not always, but often - a constant top view, and not an explicit copy. However, it is often smarter than your average list - for example, it will use efficient contains support collection methods.

+2
source

javolution have thread safe fastmap

0
source

All Articles