Question

I need some class/interface name that describes an immutable, ordered set (in input order, like LinkedHashSet). I can of course just use the class like this:

class Foo {
    public final Set<Long> frozenOrderedSet;

    public Foo(List<Long> input) {
        frozenOrderedSet = Collections.unmodifiableSet(new LinkedHashSet(input));
    }
}

But this would not clarify my approach. I would like to make it clear to everyone reading the source that the Set is unmodifiable and unique while maintaining it's order with for(Long l : set){}.

Was it helpful?

Solution

Guava's ImmutableSet provides a high-performance, immutable Set with reliable, user-specified iteration order. There are also variations like ImmutableSortedSet.

OTHER TIPS

The simplest way would be extend Set to create a custom immutable Set.

public CustomImmutableSet(){ return Collections.unmodifiableSet(new LinkedHashSet(input)); }

This way it will make it clear to everyone reading the source that the Set is unmodifiable and unique

Bozho in question Java Immutable Collections:

Unmodifiable collections are usually read-only views (wrappers) of other collections. You can't add, remove or clear them, but the underlying collection can change.

Immutable collections can't be changed at all - they don't wrap another collection - they have their own elements.

Here's a quote from guava's ImmutableList

Unlike Collections.unmodifiableList(java.util.List), which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change.

So, basically, in order to get an immutable collection out of a mutable one, you have to copy its elements to the new collection, and disallow all operations.

So Basically you might create subclass of class TreeSet and override all :add, remove etc. methods to just throw an Exception saying that this is immutable collection. Also you would have to create copying constructor in this class with one parameter TreeSet setToCopyFrom.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top