Javatpoint Logo
Javatpoint Logo

Immutable List in Java

In Java, an immutable list is a list that cannot be modified once it is created. An attempt to add, remove, or modify elements in the List after it is created will throw an exception.

The primary benefit of using immutable lists is that they provide thread safety and make the code more robust. Since the List cannot be modified after it is created, there is no risk of multiple threads trying to modify it simultaneously and causing issues. Additionally, immutable lists can be easily shared among different program parts without fear of being unintentionally modified.

Overall, using immutable lists in Java can improve the safety and robustness of a program, especially in multi-threaded environments where shared data structures can cause issues.

Class Declaration

In Java, the ImmutableList class is a part of the Guava library, which provides several immutable collection classes. To use ImmutableList, we first import the com.google.common.collect the package containing the ImmutableList class.

The class declaration of ImmutableList is as follows:

ImmutableList extends the ImmutableCollection class and implements the List interface. It is a generic class, which means we can create an ImmutableList of any data type. The E in the declaration represents the type parameter, which we can replace with any class or interface name.

Class hierarchy

The ImmutableList class implements the List interface and represents a list that cannot be modified once created.

The class hierarchy of ImmutableList is as follows:

Here, ImmutableCollection is an abstract class that provides a skeletal implementation of the ImmutableCollection interface, which ImmutableList extends.

Overall, the ImmutableList class provides a convenient and efficient way to create and use immutable lists in Java.

Creating ImmutableList

There are different ways to create an ImmutableList in Java, depending on the version of Java you are using and the libraries you have available. Here are some examples:

1. Using the Java 9 of() method:

Java 9 introduced a new method called of() in the List interface, which creates immutable lists more concisely and readably. The of() method is a factory method that takes a variable number of arguments and returns an immutable list containing those elements. It can be used with any class that implements the List interface, including ArrayList, LinkedList, and ImmutableList. One advantage of using the of() method is that it is much more concise and provides compile-time safety by performing type inference on the arguments, ensuring that only objects of the correct type are added to the List. Overall, the of() method simplifies the creation of immutable lists in Java.

The steps to find the solution is mentioned below.

  1. Import the List class from the Java.util package: Which allows the program to use the List interface to create and manipulate lists of objects.
  2. Create an immutable list using the Java 9 factory method: The code uses the List.of() method to create an immutable list of strings with four elements.
  3. Attempt to modify the List: The program tries to add an element to the immutable list using the add() method, which is not allowed on immutable lists. As a result, the program catches the UnsupportedOperationException thrown by the add() method and prints a message indicating that the list cannot be modified.

Filename: ImmutableListExample.java

Output:

Fruits: [apple, banana, orange, grape]
Cannot modify immutable List.

2. Using the ImmutableList.Builder class from the Guava library:

Adding elements to the List in a fluent style, making it convenient for incrementally creating a list.

Regardless of the method used, the resulting ImmutableList can be accessed and iterated over like any other list, but its contents cannot be modified.

Here is the stepwise solution for the given code:

  1. Import the required classes: Import the List interface and the ImmutableList class from the com.google.common.collect package.
  2. Create an immutable list using the builder: Create an immutable list using the ImmutableList builder. Use the add() method to add elements to the List, and call the build() method to create an immutable list.
  3. Create an immutable list from an existing list: Create a List object with the desired elements. Then call the ImmutableList.copyOf() method, passing the List as a parameter, to create an immutable list.
  4. Adding more elements: Use the ImmutableList builder to add more elements using the addAll() method, and call the build() method to create an immutable list.
  5. Print the lists: Use the System.out.println() method to print the contents of the immutable lists.

Implementation:

Filename: ImmutableListExample.java

Output:

Immutable List 1: [Welcome, to, home]
Immutable List 2: [Welcome, to, home, Think]
Immutable List 3: [Welcome, to, home, Think, Big]

3. By using of() method of ImmutableList class

The of() method of the ImmutableList class in the Guava library allows you to create an immutable list with a fixed number of elements. Once the List is created, you cannot add, remove or modify its elements.

Filename: ImmutableListExample.java

Output:

Fruits: [apple, banana, orange, grape]

4. By use of copyOf() method

In Java, the copyOf() method creates a new array that copies an existing array with a specified length. The method takes two arguments: the array to be copied and the length of the new array.

Filename: ImmutableListExample.java

Output:

Immutable List 1: [Java, Python, C++]
Immutable List 2: [Learning, Web, Development, is, Fun]

5. UnsupportedOperationException

The program illustrates creating an immutable list in Java using the Collections.unmodifiableList method. Additionally, it shows how to handle the UnsupportedOperationException that is thrown when trying to modify the List.

The steps to find the solution is mentioned below:

  1. First, we create a mutable ArrayList containing some initial elements using the of method, which returns an immutable list. We then pass this ArrayList to the Collections.unmodifiableList method, which returns an immutable view of the List.
  2. We attempt to modify the immutable List using the add, remove, and set Since the List is immutable, attempting to modify it will throw an UnsupportedOperationException.
  3. We catch the UnsupportedOperationException that is thrown and print a message to the console indicating which operation was attempted and was unsuccessful.

Note that the Collections.unmodifiableList method only creates an immutable view of the original List. The immutable view will reflect those changes if the original List is modified. To create a truly immutable list that cannot be modified by any means, you can use a custom implementation of the List interface that throws an exception when attempting to modify the List.

Implementation:

Filename: ImmutableListExample.java

Output:

UnsupportedOperationException: null
UnsupportedOperationException: null
UnsupportedOperationException: null

6. Collections.unmodifiableList()

Collections.unmodifiableList() is a method in the Java Collections Framework that creates an unmodifiable view of an existing list. It can be inferred that trying to modify the unmodifiable List will lead to the occurrence of an UnsupportedOperationException. The original List can still be modified, and any changes will be reflected in the unmodifiable List.

The program showcases how to utilize the Collections.unmodifiableList() method to generate an unmodifiable representation of a mutable list.

The steps to find the solution is mentioned below:

  1. Create a mutable list mutableList and add some elements to it using the add() method of the ArrayList
  2. Create an unmodifiable view of the mutable list mutableList using the unmodifiableList() method and assign it to the variable unmodifiableList.
  3. Attempt to modify the unmodifiable list unmodifiableList using the add() Since the unmodifiable List is read-only, this will throw an UnsupportedOperationException. A message is printed to the console after catching this exception.
  4. Modify the original mutable list mutableList by adding another element using the add()
  5. Print both the mutable and unmodifiable lists to the console to show that the unmodifiable List reflects the changes made to the original mutable List.

Filename: UnmodifiableListExample.java

Output:

Attempt to modify unmodifiableList failed: null
mutableList: [apple, banana, orange, pear]
unmodifiableList: [apple, banana, orange, pear]

Advantages of ImmutableList

ImmutableList has several advantages, including:

  1. Thread-safety: Since ImmutableList is immutable, it is inherently thread-safe. Multiple threads can access the same List without any risk of thread interference or memory inconsistency.
  2. Security: Immutable lists are less prone to security vulnerabilities. For instance, if an attacker tries to modify the List by adding or removing elements, they cannot do so as the List is immutable.
  3. Performance: Since immutable lists are read-only, they can be cached for better performance. If a list needs to be accessed multiple times, using an immutable list instead of creating a new list each time can help avoid overhead.
  4. Predictability: Since immutable lists cannot be modified, their behaviour is predictable. Some benefits of using immutable lists are eliminating the need for defensive programming and making it easier to reason about the code.
  5. Simplifies coding: Immutable lists simplify coding by eliminating the need for synchronization, defensive copying, and error-prone manual memory management. The result of this approach is code that is easier to maintain and has a cleaner appearance.
  6. Facilitates testing: Immutable lists are easier to test since their contents do not change. The approach makes writing tests that cover all possible scenarios and edge cases easier.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA