Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class that describes a immutable, ordered set

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){}.

like image 664
WorldSEnder Avatar asked Jul 28 '14 22:07

WorldSEnder


People also ask

Are immutable sets ordered?

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?

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.

What is immutable collection in Java?

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.

Is Arraylist immutable in Java?

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.


2 Answers

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

like image 137
Steven Schlansker Avatar answered Sep 28 '22 09:09

Steven Schlansker


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

like image 37
rupesh jain Avatar answered Sep 28 '22 08:09

rupesh jain