Skip to content
Related Articles

Related Articles

Improve Article

Immutable Set in Java

  • Difficulty Level : Easy
  • 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

  • Using copyOf() method in Guava We use an existing Set to create an ImmutableSet.




    // Creating an immutable set using copyOf()
    import java.util.*;
    import com.google.common.collect.ImmutableSet;
    import java.io.*;
      
    class GfG
    {
        public static void main(String args[])
        {
            // creating empty set
            Set<String> s = new HashSet<String>();
            s.add("GeeksforGeeks");
            s.add("Practice");
              
            // An immutable copy of s
            Set<String> is  = ImmutableSet.copyOf(s);
                
            System.out.println(is);
        }
    }

    Output :

    [GeeksforGeeks, Practice]
  • Using Of() method in Guava




    // Java code illustrating of() method to
    // create a ImmutableSet
    import java.util.*;
    import com.google.common.collect.ImmutableSet;
      
    class GfG
    {
        public static void main(String args[])
        {          
            // non-empty immutable set
            ImmutableSet<String> is = 
                     ImmutableSet.of("ide", "code");
                
            // Lets try adding element in these set
            System.out.println(is);             
        }
    }

    Output :

    [ide, code]
  • Using Java 9 Factory Of() method
    In Java, if we use of with Set, Map or List, an Immutable Set is created.




    // Java code illustrating of() method to
    // create a ImmutableSet
    import java.util.*;
    import com.google.common.collect.ImmutableSet;
      
    class GfG
    {
        public static void main(String args[])
        {          
            // non-empty immutable set
            Set<String> is = Set.of("ide", "code");
                
            // Let's print the set
            System.out.println(is);             
        }
    }

    Output :



    [ide, code]

What if we try to change an ImmutableSet?
It throws UnsupportedOperationException




// Java code illustrating of() method
import java.util.*;
  
class GfG
{
    public static void main(String args[])
    {
        // empty immutable set
        Set<String> is1 = Set.of();
            
        // non-empty immutable set
        Set is2 = Set.of("ide", "contribute", "support");
            
        // Lets try adding element in these set
        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.




// Java program to demonstrate that a set created using
// Collections.unmodifiableSet() can be modified indirectly.
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);
  
        // We change s and the changes reflect in us.
        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.




// Creating an immutable set using copyOf()
// and modifying original set.
import java.util.*;
import com.google.common.collect.ImmutableSet;
import java.io.*;
  
class GfG
{
    public static void main(String args[])
    {
        // creating empty set
        Set<String> s = new HashSet<String>();
        s.add("GeeksforGeeks");
        s.add("Practice");
          
        // An immutable copy of s
        Set<String> is  = ImmutableSet.copyOf(s);
            
        // Now if we change 's', 'is' does not change
        s.add("Contribute");
        System.out.println(is);
    }
}

Output :

[GeeksforGeeks, Practice]

Reference
Creating Immutable Lists, Sets, and Maps

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :