Java: copy-on-write data structure?

Is there anything in Java that implements something like the following

interface MSet<T> extends Iterable<T> {
    /**
     * return a new set which consists of this set plus a new element.
     * This set is not changed.
     */
    MSet<T> add(T t);

    /**
     * return a new set which consists of this set minus a designated element.
     * This set is not changed.
     */
    MSet<T> remove(T t);
}

      

edit: I need something like this CopyOnWriteArraySet

, except that the class is changed and I want something that is an immutable set that allows a new set to be created. The reason for this is because I need to pass references to the old set and leave them unchanged.

edit 2: how does Scala implement scala.collection.immutable.Set ? This is the behavior I want, I just don't want to suck in all of Scala just for this.

+2


a source to share


3 answers


Use the Google Collections Library Immutable*

for all your immutable collection needs. My guess is that you need a lightweight class that can be easily done with Forwarding*

(also in GC) that spawns new immutable (or mutable, whatever) add / remove operations. Finally, if your changes do not need to be allowed to create new modifications, you can implement these operations using various options in the static compilation sub-libraries in the GC (Iterables, Lists, Sets, etc.) to get the views (re sets: union, intersection, filter).



edit: however, google code is currently slow, it might take a little to test it.

+2


a source


CopyOnWriteArraySet is similar. However, copying is internal, so it doesn't return a reference to the new object.



0


a source


Java has copy-on-write data structures such as CopyOnWriteArrayList , however the API is slightly different from what you suggested; instead of returning a new object, it has the same API as other collections, but just creates a separate copy of the array internally. '

There is no out-of-the-box API type that you want; however, this should be fairly trivial to implement; just duplicate the collection, mutate on the duplicate and return it.

0


a source







All Articles