Immutable List in Java10 Sept 2024 | 9 min read 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 DeclarationIn 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 hierarchyThe 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 ImmutableListThere 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.
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:
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 classThe 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() methodIn 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. UnsupportedOperationExceptionThe 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:
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:
Filename: UnmodifiableListExample.java Output: Attempt to modify unmodifiableList failed: null mutableList: [apple, banana, orange, pear] unmodifiableList: [apple, banana, orange, pear] Advantages of ImmutableListImmutableList has several advantages, including:
Next TopicNesting Of Methods in Java |
Various Operations on Queue Using Stack in Java
Fundamental data structures used in computer programming to organise collections of elements in a specific sequence include queues and stacks. The use of two stacks to create a queue is feasible even though they are typically used separately. This essay will examine the different operations that...
4 min read
DoubleBuffer hasArray() method in Java with Examples
The java.nio.DoubleBuffer contains hasArray() function. The DoubleBuffer class is utilized to verify if the provided buffer is supported by a float array that may be accessed. If a backing array for this buffer is reachable, it returns true; otherwise, it returns false. The array() and arrayOffset()...
3 min read
Multiset Interface in Java
In Java, basic sets like HashSet belong to Java. Through its use of the tilde symbol, a util package, and the mathematical properties of a set, which are that its members are different and not repeatable. But there are some use cases like frequency table, which is...
7 min read
Generational ZCG in Java 21
Garbage collection is a crucial aspect of memory management in modern programming languages, and Java is no exception. Java's Garbage Collector (GC) automatically manages memory by reclaiming objects that are no longer in use. In Java 21, the garbage collection process has seen significant improvements, especially...
3 min read
Java Program to Check if a Number is Positive or Negative
In this section, we will write the Java programs to check if a number is positive or negative. We have used the following ways to check the number is positive, negative, or zero. Using Relational Operator Using Math.signum() Method Using Integer.signum() Method Using Bit Shift Operator Using ArrayList class Using Relational Operator To...
5 min read
Computing Digit Sum of All Numbers From 1 to n in Java
In this section, we will discuss the methods to compute digit sum of all numbers from 1 to n in through Java program. Example: Input: num = 7 Output: Sum of all the digits occurring in the numbers from 1 to 7 is: 1 + 2 + 3 + 4 +...
9 min read
Java Localization
Internationalization is the process of developing a software application so that it can be altered to various languages and regions without modifying the application. Developing an application locale specific increases, the cost of the application, also require lots of maintenance. Localization is the process of adapting internationalized...
10 min read
Lucky Number in Java
In this section, we will learn what is a luck number and also create Java programs to check if the given number is a lucky number or not. The lucky number program frequently asked in Java coding tests and academics. Lucky Number The sequence of natural numbers or...
3 min read
Program to Generate CAPTCHA and Verify User Using Java
CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a security mechanism widely used to differentiate between human users and automated bots. It presents a challenge to users in the form of distorted text or images that must be deciphered correctly. In...
4 min read
Java Program to Check Given Matrix is Magic Square or Not
A magic square is a square matrix (an (n times n) grid) of unique positive integers organized in such a way that the total of the numbers in each row, column, and both main diagonals is equal. This constant sum is known as the magical constant....
7 min read
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India