Immutable Set in Java
Last Updated :
11 Dec, 2018
- As the name suggest these Set are immutable.
- If any attempt made to add, delete and update elements in the set we will have UnsupportedOperationException.
- An ImmutableSet does not allow null element either.
- If any attempt made to create an ImmutableSet with null element, we will have NullPointerException. If any attempt made to add null element in set, we will have UnsupportedOperationException.
- One advantage of any immutable collection (Set, Map, List) is thread safety. These are automatically thread sage as they are immutable.
- Note that it is an immutable collection, not collection of immutable objects, so the objects inside it can be modified.
Creating an ImmutableSet in Java
What if we try to change an ImmutableSet?
It throws UnsupportedOperationException
import java.util.*;
class GfG
{
public static void main(String args[])
{
Set<String> is1 = Set.of();
Set is2 = Set.of( "ide" , "contribute" , "support" );
is1.add( null );
is2.add( "set" );
}
}
|
Output :
Exception in thread "main" java.lang.UnsupportedOperationException
at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:218)
at ImmutableListDemo.main(Main.java:16)
How is it different from Collections.unmodifiableSet()?
Collections.unmodifiableSet creates a wrapper around the same existing set such that the wrapper cannot be used to modify it. However we can still change original Set.
import java.io.*;
import java.util.*;
class GFG {
public
static void main(String[] args)
{
Set<String> s = new HashSet<String>();
s.add( "Geeks" );
Set<String> us = Collections.unmodifiableSet(s);
s.add( "Practice" );
s.add( "Contribute" );
System.out.println(us);
}
}
|
Output:
[Geeks, Practice, Contribute]
If we create an ImmutableSet from an existing set and change the existing set, the Immutable Set does not change because a copy is created.
import java.util.*;
import com.google.common.collect.ImmutableSet;
import java.io.*;
class GfG
{
public static void main(String args[])
{
Set<String> s = new HashSet<String>();
s.add( "GeeksforGeeks" );
s.add( "Practice" );
Set<String> is = ImmutableSet.copyOf(s);
s.add( "Contribute" );
System.out.println(is);
}
}
|
Output :
[GeeksforGeeks, Practice]
Reference
Creating Immutable Lists, Sets, and Maps
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...