Home > Java > javaTutorial > body text

What are the benefits of immutable collections in Java 9?

PHPz
Release: 2023-09-07 10:45:03
forward
899 people have browsed it

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>
Copy after login

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);
   }
}
Copy after login

Output

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!