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 |
Generating a random string in Java is a simple concept which is often required to build Ids, temporary passwords, session tokens or any other case where the alphanumeric string is most electronically required. There are several ways to achieve this using the different classes and...
13 min read
Problem Statement N ferocious fish are swimming along a river. Every fish has a weight and a direction of travel. Each member in the one-dimensional array that represents the river is a fish. The fish may swim upstream or downstream. Large fish will devour the smaller ones...
5 min read
When an I/O operation attempts to occur on a closed channel, or a channel that is closed to the intended operation, the class ClosedChannelException is triggered. That is, if this exception is thrown. It does not mean, however, that the channel is totally closed-just that the...
4 min read
Java is a versatile and powerful programming language known for its strong type system. One of the key features that enhances type safety and promotes code reusability is bounded types. Bounded types allow developers to impose constraints on the types that can be used as generic...
5 min read
The object is a basic building block of an OOPs language. In Java, we cannot execute any program without creating an object. There is various way to create an object in Java that we will discuss in this section, and also learn how to create an...
6 min read
Given a string "str," our task is to create a lexicographically first palindromic string by rearranging the characters in the given text. If there isn't a string of that type, then the message "no such palindromic string exists" will be returned. Example 1: Input: String str = "madam" Output: The lexicographic...
4 min read
Patterns are considered one of the more popular topics in programming where one of the chief goals involves testing an ability to build logic. Loops are most commonly used for their implementation, although this article describes a method of printing the desired pattern without loops and...
4 min read
In Java, object calling can be considered as an important concept related to object-oriented programming (OOP). The process of object calling gets started by the instantiation of a class, which is utilized for representation of a blueprint that can be later utilized for the creation of...
7 min read
Java technology does not require an introduction. Everyone around the world is still amazed at the astonishing power of Java in web and mobile development. Of course, you too may be tempted by Java's popularity and monopoly in software development, and you may want to use...
8 min read
In Java, there are various methods for creating and accessing text files. It is necessary to do this when working with numerous apps. Java has multiple methods for reading plain text files, such as FileReader, BufferedReader, and Scanner. Each utility offers a unique feature; for example,...
4 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