[Learning JAVA from scratch | Article 28] Immutable collections

Table of contents

Table of contents

Foreword:

Immutable collections:

Common immutable collections:

1. Create an immutable collection of lists:

2. Create an immutable collection of maps:

Application scenario:

Summarize:


Foreword:

        In this article, we will introduce the immutable collection in JAVA, which locks the content and cannot change the content at will. It is a very common content section in JAVA, and everyone should have a good grasp of it.

Immutable collections:

        In Java, an immutable collection is a collection that cannot be modified once created . This means that the elements in an immutable collection are fixed and cannot be added, removed or modified. The main advantages of immutable collections are thread safety and higher performance .

thread safety:

        Thread safety means that when an operation is performed in a multi-threaded environment, the operation can be performed correctly without causing inconsistent or indeterminate results . Simply put, thread safety ensures the correctness and consistency of data when multiple threads access or modify shared data at the same time.

        Thread safety is to ensure the correctness and consistency of data shared between multiple threads by using synchronization, locks, atomic operations, or thread-safe data structures . In a multi-threaded environment, properly handling thread safety issues can avoid problems such as race conditions, data races, and deadlocks.

Common immutable collections:

1. Create an immutable collection of lists:

In Java, there are several ways to create an immutable List collection:

1. Use  the Collections.unmodifiableList()  method:

List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");

List<String> immutableList = Collections.unmodifiableList(list);

This method converts an ordinary mutable List into an immutable List. Although the underlying data can be modified through the original list, modification operations on immutable lists will throw an `UnsupportedOperationException` exception.

2. Use  Guava's ImmutableList.of()   method:

ImmutableList<String> immutableList = ImmutableList.of("apple", "banana", "orange");

The `ImmutableList` class provided by the Guava library provides an easy and convenient way to create immutable lists. This method accepts any number of elements as a parameter and returns an immutable List collection.

3. Use the new List.of() method in Java 9:

List<String> immutableList = List.of("apple", "banana", "orange");

In Java 9, the `List.of()` method has been added to allow the direct creation of immutable List collections. Similar to Guava's `ImmutableList.of()` method, it accepts any number of elements as an argument and returns an immutable List.

These methods can create an immutable List collection, ensuring that the contents of the collection cannot be modified after creation. Note that if you try to modify an immutable list, an exception will be thrown. Therefore, when choosing which method to use, the choice should be based on the situation and personal preference.

2. Create an immutable collection of maps:

In Java, there are several ways to create an immutable collection of Maps:

1. Use  the Collections.unmodifiableMap()   method:

Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);

Map<String, Integer> immutableMap = Collections.unmodifiableMap(map);


This method converts an ordinary mutable Map into an immutable Map. Although the underlying data can be modified through the original map, modification operations on the immutable map will throw an `UnsupportedOperationException` exception.

2. Use  Guava's ImmutableMap.of()   method:

ImmutableMap<String, Integer> immutableMap = ImmutableMap.of("apple", 1, "banana", 2, "orange", 3);

The `ImmutableMap` class provided by the Guava library provides an easy and convenient way to create immutable Maps. This method accepts key-value pairs as parameters and returns an immutable Map collection.

3. Use the newly added  Map.of()  method in Java 9:

Map<String, Integer> immutableMap = Map.of("apple", 1, "banana", 2, "orange", 3);

In Java 9, the `Map.of()` method has been added to allow the direct creation of immutable Map collections. Similar to Guava's `ImmutableMap.of()` method, it accepts key-value pairs as parameters and returns an immutable Map.

These methods can create an immutable Map collection, ensuring that the contents of the collection cannot be modified after creation. It should be noted that if you try to perform a modification operation on the immutable map, an exception will be thrown. Therefore, when choosing which method to use, the choice should be based on the situation and personal preference.

Application scenario:

Immutable collections are widely used in many scenarios, the following are some common application scenarios:

1. Multi-threaded environment: In a multi-threaded environment, immutable collections are thread-safe. Multiple threads can access and read immutable collections concurrently without additional synchronization mechanisms. This improves concurrency performance and reduces problems with thread contention and data inconsistency.

2. Caching: The application of immutable collections in caching is very common. For example, using immutable collections to store cached data avoids the problems of data modification and synchronization in the cache. This improves the performance and reliability of the cache.

3. Method return value: An immutable collection can be used as the return value of a method to ensure that the method caller cannot modify the returned collection. This approach can provide security and stability, preventing data from being accidentally modified during method calls.

4. Configuration information: Immutable collections are often used to store configuration information. Loading configuration information into an immutable collection at one time ensures that the configuration information will not be accidentally modified, and provides consistency and reliability.

5. The key of the hash table: the immutable collection can be used as the key of the hash table to ensure the uniqueness of the key and the stability of the hash value. Since the elements of an immutable collection are immutable, the keys in the hash table are guaranteed to remain the same.

6. Functional programming: Immutable collections are an important concept in functional programming. Functional programming encourages the use of immutable data structures and pure functions. Immutable collections ensure no side effects and support composition and concurrent execution of functions.

It should be noted that although immutable collections are useful in the above scenarios, they are not suitable for all situations. In some scenarios where the collection needs to be modified and updated frequently, mutable collections may be more appropriate. Therefore, it is necessary to choose whether to use a mutable collection or an immutable collection according to specific application requirements and performance requirements.

Summarize:

        An immutable collection refers to a collection that cannot be modified after creation, and has the following characteristics and advantages: 1. Stability and consistency of data, avoiding accidental modification. 2. Thread-safe, no additional synchronization required. 3. Efficient query and retrieval can improve performance by optimizing hash and equality operations. 4. Can be safely used as a key, providing better consistency and stability. 5. Simplifies coding and maintenance, reducing the need for defensive copy and synchronization operations. Immutable collections are a reliable, efficient, and easy-to-use data structure for scenarios that require data immutability and thread safety.

If my content is helpful to you, please like, comment and bookmark . Creation is not easy, everyone's support is my motivation to persevere!

Guess you like

Origin blog.csdn.net/fckbb/article/details/131712951