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){}
.
Sets have no defined order, because they're not indexed collections. Immutable. js has an OrderedSet collection type that acts like an OrderedMap . It preserves the insertion order of its values.
What Is an Immutable Set? In general, an immutable object will not change its internal state once we create it. This makes it thread-safe by default. The same logic applies to immutable sets.
An object is considered immutable if its state cannot change after it is constructed. After you create an immutable instance of a collection, it holds the same data as long as a reference to it exists.
No, you cannot make the elements of an array immutable. But the unmodifiableList() method of the java. util. Collections class accepts an object of the List interface (object of implementing its class) and returns an unmodifiable form of the given object.
Guava's ImmutableSet provides a high-performance, immutable Set with reliable, user-specified iteration order.
There are also variations like ImmutableSortedSet.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With