Sunday, August 14, 2022

Unmodifiable or Immutable Set in Java

A Set is considered unmodifiable if elements cannot be added, removed, or replaced from the Set once the unmodifiable instance of a Set is created. In this post we’ll see how Unmodifiable Set was created before Java 9 and how it can be created Java 9 onward using Immutable Set Static Factory Methods.

Creating Unmodifiable Set before Java 9

Till Java 8 in order to create unmodifiable Set Collections.unmodifiableSet() method was used.

  • Collections.unmodifiableSet(Set<? extends T> s)- Returns an unmodifiable view of the specified set.

Drawback of this method is that the underlying Set is still modifiable let’s try to see it with an example.

public class UnmodifiableSet {
  public static void main(String[] args) {
    Set<String> alphaSet = new HashSet<>();
    alphaSet.add("a");
    alphaSet.add("b");
    alphaSet.add("c");
    alphaSet.add("d");
    Set<String> aSet = Collections.unmodifiableSet(alphaSet);
    alphaSet.add("e");
    System.out.println("alphaSet- " + alphaSet);
    //error as this set is an unmodifiable view
    aSet.add("f");
  }
}

Output

alphaSet- [a, b, c, d, e] Exception in thread "main" 
java.lang.UnsupportedOperationException
 at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1058)
 at org.netjs.Programs.UnmodifiableSet.main(UnmodifiableSet.java:19)

In the example aSet is an unmodifiable view of the alphaSet. You can still modify the underlying set alphaSet though error is thrown if any modification is done to the unmodifiable view.

Creating Unmodifiable Set in Java 9

The Set.of (added in Java 9) and Set.copyOf (added in Java 10) Immutable static factory methods provide a convenient way to create unmodifiable sets. The Set instances created by these methods have the following characteristics-

  1. The Set returned by the convenience factory method added in JDK 9 is conventionally immutable. Elements cannot be added, removed, or replaced from such a Set. Calling any mutator method on the Set will always cause UnsupportedOperationException to be thrown.
  2. If the contained elements in the Set are mutable, this may cause the Set's contents to appear to change.
  3. Immutable Sets created using static factory methods disallow null elements. Attempts to create them with null elements result in NullPointerException.
  4. They reject duplicate elements at Immutable Set creation time. Duplicate elements passed to a static factory method result in IllegalArgumentException.
  5. They are serializable if all elements are serializable.
  6. The iteration order of set elements is unspecified and is subject to change.

Java Set.of() methods for creating unmodifiable set

Set.of() static factory method is a convenient way to create unmodifiable sets Java 9 onward. This method has both fixed-argument form and varargs form. Fixed-argument form overloads up to 10 elements and the form of this method is as follows.

Set.of()- Returns an unmodifiable set containing zero elements. 
Set.of(E e1)- Returns an unmodifiable set containing one element.
..
..
Set.of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)- Returns an unmodifiable set containing nine elements. 
Set.of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)- Returns an unmodifiable set containing ten elements.

varargs form

  • Set.of(E... elements)- Returns an unmodifiable set containing an arbitrary number of elements.

Set.of() method Java example

public class UnmodifiableSet {
  public static void main(String[] args) {
    Set<String> alphaSet = Set.of("a", "b", "c", "d");
    System.out.println("alphaSet- " + alphaSet);
    //error as this set itself is immutable
    alphaSet.add("e");
  }
}

Output

alphaSet- [d, c, b, a]
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:72)
 at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:76)
 at org.netjs.Programs.UnmodifiableSet.main(UnmodifiableSet.java:13)

Set.copyOf() method in Java

If you want to create an unmodifiable Set using an existing collection then you can use copyOf() method.

public class UnmodifiableSet {
  public static void main(String[] args) {
    Set<String> alphaSet = new HashSet<>();
    alphaSet.add("a");
    alphaSet.add("b");
    alphaSet.add("c");
    alphaSet.add("d");
    System.out.println("alphaSet- " + alphaSet);
    Set<String> aSet = Set.copyOf(alphaSet);
    System.out.println("aSet- " + alphaSet);
    //error as this set is unmodifiable
    aSet.add("f");
  }
}

Output

alphaSet- [a, b, c, d]
aSet- [a, b, c, d]
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:72)
 at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:76)
 at org.netjs.Programs.UnmodifiableSet.main(UnmodifiableSet.java:19)

That's all for this topic Unmodifiable or Immutable Set in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How HashSet Works Internally in Java
  2. How to Sort HashSet in Java
  3. CopyOnWriteArraySet in Java With Examples
  4. Unmodifiable or Immutable List in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Java ArrayBlockingQueue With Examples
  2. Synchronization in Java - Synchronized Method And Block
  3. Optional Class in Java With Examples
  4. Array in Java With Examples
  5. static Block in Java
  6. Configuring DataSource in Spring Framework
  7. Spring MVC Excel Generation Example
  8. Class And Object in Python

No comments:

Post a Comment