Immutable Set in Java

  • 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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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);
        }
    }

    chevron_right

    
    

    Output :

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

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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);             
        }
    }

    chevron_right

    
    

    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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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);             
        }
    }

    chevron_right

    
    

    Output :

    [ide, code]

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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");             
    }
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output :

[GeeksforGeeks, Practice]

Reference
Creating Immutable Lists, Sets, and Maps



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.