What are the conditions for Collection factory methods in Java 9?

JavaObject Oriented ProgrammingProgramming

In Java 9, factory methods have been added to Collections API. We can create an unmodifiable list, set and map collection objects in order to reduce the number of lines of code by using it. The List.of(), Set.of(), Map.of(), and Map.ofEntries() are the static factory methods provides convenient way of creating immutable collections.

Below are the conditions for Collection factory methods:

  • They are structurally immutable.
  • They disallow null elements or null keys.
  • They are serializable if all elements are serializable.
  • They reject duplicate elements/keys at creation time.
  • The Iteration order of set elements is unspecified and is subject to change.
  • They are value-based. Factories are free to create new instances or reuse existing ones. Therefore, Identity-sensitive operations on these instances, Identity hash code, and synchronization are unreliable and can be avoided.

Syntax

List.of(elements...)
Set.of(elements...)
Map.of(k1, v1, k2, v2)

Example

import java.util.Set;

public class CollectionsTest {
   public static void main(String args[]) {
      System.out.println("Java 9 Introduced a static factory method: of()");
      Set<String> immutableCountrySet = Set.of("India", "England", "South Africa", "Australia");
      System.out.println(immutableCountrySet);
      try {
         immutableCountrySet.add("Newzealand");
      } catch(Exception e) {
         System.out.println("Caught Exception, Adding Entry to Immutable Collection!");
      }
   }
}

Output

Java 9 Introduced a static factory method: of()
[South Africa, India, Australia, England]
Caught Exception, Adding Entry to Immutable Collection!
raja
Published on 03-Apr-2020 10:33:04
Advertisements