Class that describes a immutable, ordered set
-
20-12-2019 - |
Pregunta
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){}
.
Solución
Guava's ImmutableSet provides a high-performance, immutable Set with reliable, user-specified iteration order.
There are also variations like ImmutableSortedSet.
Otros consejos
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
.