Home  >  Article  >  Java  >  What are the benefits of immutable collections in Java 9?

What are the benefits of immutable collections in Java 9?

PHPz
PHPzforward
2023-09-07 10:45:03900browse

Java 9中的不可变集合有哪些好处?

In Java 9, Collections API added several factory methods. By using these factory methods, we can create unmodifiable list, collection, and mapped collection objects, thus reducing the number of lines of code. In Java 9, List.of(), Set.of(), Map.of() and Map.ofEntries() are provided for convenience Static factory method, used to create immutable collections.

Benefits of immutable collections

  • Less heap space: Required to store collection data compared to the traditional approach in earlier versions of Java Very little space.
  • Faster data access: Data access is now faster due to the reduced overhead of storing data and wrapping it as Collections.unmodifiable. This means that the overall efficiency of the program increases.
  • Thread safety: Immutable collections are naturally thread-safe. Because all threads always get the same view of the underlying data. The Chinese translation of

Grammar

<strong>List.of(elements...)
Set.of(elements...)
Map.of(k1, v1, k2, v2)
</strong>

Example

is:

Example

import java.util.Set;
import java.util.List;
import java.util.Map;
public class ImmutableCollectionsTest {
   public static void main(String args[]) {
      <strong>List<String></strong> stringList = <strong>List.of</strong>("a", "b", "c");
      System.out.println("List values: " + stringList);
      <strong>Set<String></strong> stringSet = <strong>Set.of</strong>("a", "b", "c");
      System.out.println("Set values: " + stringSet);
      <strong>Map<String, Integer></strong> stringMap = <strong>Map.of</strong>("a", 1, "b", 2, "c", 3);
      System.out.println("Map values: " + stringMap);
   }
}

Output

<strong>List values: [a, b, c]
Set values: [a, b, c]
Map values: {a=1, b=2, c=3}</strong>

The above is the detailed content of What are the benefits of immutable collections in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete