Class CollectionFactoryMethodsDemo

java.lang.Object
modernfeatures.java9.collections.CollectionFactoryMethodsDemo

public class CollectionFactoryMethodsDemo extends Object
Demonstrates the use of Java 9 collection factory methods.

Java 9 introduced convenient static factory methods for creating immutable collections:

  • List.of()
  • Set.of()
  • Map.of()
These methods allow concise creation of collections that are unmodifiable (immutable). Attempting to modify them results in UnsupportedOperationException.

Example usage:

   List<String> names = List.of("Alice", "Bob", "Carol");
   Set<Integer> numbers = Set.of(1, 2, 3, 4, 5);
   Map<String, Integer> ages = Map.of("Alice", 30, "Bob", 25);
 
  • Constructor Details

    • CollectionFactoryMethodsDemo

      public CollectionFactoryMethodsDemo()
  • Method Details

    • main

      public static void main(String[] args)
      Demonstrates creation of immutable collections using Java 9 factory methods, and shows that modification attempts result in exceptions.

      This method performs the following steps:

      • Creates an immutable List using List.of() and prints it.
      • Creates an immutable Set using Set.of() and prints it.
      • Creates an immutable Map using Map.of() and prints it.
      • Attempts to modify each collection to demonstrate that they throw UnsupportedOperationException.
      Parameters:
      args - command-line arguments (not used)