In the last tutorial, we learned how to create immutable lists with ease using the factory methods introduced in Java 9. In this guide, we will see the use of newly introduced factory methods to create immutable Sets.
1. Creating immutable Set prior to Java 9
Before we discuss how to use the factory methods to create unmodifiable Sets, lets see how we used to create immutable set prior to Java 9.
1.1 Creating empty immutable Set before java SE 9
Prior to Java 9, we have to use unmodifiableSet() method of Collections class to create immutable Set. In the following example we are creating an empty set.
Set<String> emptyHashSet = new HashSet<String>(); Set<String> immutableHSet = Collections.unmodifiableSet(emptyHashSet);
Lets test this code in JShell (a new tool introduced in Java 9)
1.2 Creating Non-empty immutable Set before Java SE 9
This is how we used to create non empty immutable Sets before Java 9. As you can see we have to write several lines of code to get this working. In Java 9 we can write this code in a single line, we will see that in the next section.
Set<String> hset = new HashSet<String>();
hset.add("Jon Snow");
hset.add("Khal Drogo");
hset.add("Daenerys");
Set<String> immutableSet = Collections.unmodifiableSet(hset);
2. Java 9 – Creating Immutable Set using static factory method of()
Java 9 introduced couple of versions of of() method to create unmodifiable Sets.
static <E> Set<E> of()
2.1 Java 9 – Creating empty immutable Set
Set<String> immutableSet = Set.of();
2.2 Java 9 – Creating Non-empty immutable Set
As you can see how simple it is to create immutable set in Java 9.
Set<String> immutableSet = Set.of("Apple", "Banana", "Orange");
3. What is an immutable Set?
1. An immutable Set doesn’t allow the add, delete and update of its elements, if we try to do that then we will get UnsupportedOperationException Exception. Lets take an example to see this.
jshell> Set immutableSet = Set.of("Paul", "Lora", "Steve"); immutableSet ==> [Paul, Lora, Steve] jshell> immutableSet.add("Harry") | java.lang.UnsupportedOperationException thrown: | at ImmutableCollections.uoe (ImmutableCollections.java:71) | at ImmutableCollections$AbstractImmutableSet.add (ImmutableCollections.java:281) | at (#2:1)
2. We cannot add null elements to an immutable Set.
jshell> Set immutableSet = Set.of("Paul", "Lora", "Steve"); immutableSet ==> [Lora, Steve, Paul] jshell> immutableSet.add(null) | java.lang.UnsupportedOperationException thrown: | at ImmutableCollections.uoe (ImmutableCollections.java:71) | at ImmutableCollections$AbstractImmutableSet.add (ImmutableCollections.java:281) | at (#2:1)
Leave a Reply