Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
CopyOnWriteArrayList in Java
Next article icon

Immutable List in Java

Last Updated : 11 Dec, 2018
Comments
Improve
Suggest changes
Like Article
Like
Report
  • ImmutableList, as suggested by the name, is a type of List which is immutable. It means that the content of the List are fixed or constant after declaration, that is, they are read-only.
  • If any attempt made to add, delete and update elements in the List, UnsupportedOperationException is thrown.
  • An ImmutableList does not allow null element either.
  • If any attempt made to create an ImmutableList with null element, NullPointerException is thrown. If any attempt is made to add null element in List, UnsupportedOperationException is thrown.

Advantages of ImmutableList

  • They are thread safe.
  • They are memory efficient.
  • Since they are immutable, hence they can be passed over to third party libraries without any problem.

Note that it is an immutable collection, not collection of immutable objects, so the objects inside it can be modified.

Class Declaration:

  @GwtCompatible(serializable=true,                 emulated=true)  public abstract class ImmutableList  extends ImmutableCollection  implements List, RandomAccess  

Class hierarchy:

  java.lang.Object    ↳ java.util.AbstractCollection        ↳ com.google.common.collect.ImmutableCollection            ↳ com.google.common.collect.ImmutableList   

Creating ImmutableList
ImmutableList can be created by various methods. These include:

  1. From existing List using copyOf() function of Guava




    // Below is the Java program to create ImmutableList
      
    import com.google.common.collect.ImmutableList;
    import java.util.*;
      
    class GFG {
      
        // Function to create ImmutableList from List
        public static <T> void iList(List<T> list)
        {
            // Create ImmutableMap from Map using copyOf()
            ImmutableList<T> immutableList =
                              ImmutableList.copyOf(list);
      
            // Print the ImmutableMap
            System.out.println(immutableList);
        }
      
        public static void main(String[] args)
        {
            List<String> list = new ArrayList<>(
                Arrays.asList("Geeks", "For", "Geeks"));
      
            iList(list);
        }
    }
     
     

    Output:

      [Geeks, For, Geeks]  
  2. New ImmutableList using of() function from Guava




    // Below is the Java program to create ImmutableList
      
    import com.google.common.collect.ImmutableList;
    import java.util.*;
      
    class GFG {
      
        // Function to create ImmutableList
        public static void iList()
        {
            // Create ImmutableList using of()
            ImmutableList<String> immutableList = 
                   ImmutableList.of("Geeks", "For", "Geeks");
      
            // Print the ImmutableMap
            System.out.println(immutableList);
        }
      
        public static void main(String[] args)
        {
            iList();
        }
    }
     
     

    Output:

      [Geeks, For, Geeks]  
  3. Using Java 9 Factory Of() method

    In Java, use of() with Set, Map or List to create an Immutable List.

    Please Note: The programs below are of Java 9. Hence you would need a Java 9 compiler to run them.




    // Java code illustrating of() method to
    // create a ImmutableSet
    import java.util.*;
    import com.google.common.collect.ImmutableList;
      
    class GfG {
        public static void main(String args[])
        {
            // non-empty immutable set
            List<String> list = List.of("Geeks", "For", "Geeks");
      
            // Let's print the list
            System.out.println(list);
        }
    }
     
     

    Output:

      [Geeks, For, Geeks]  
  4. Using Builder() from ImmutableList

    In Guava, ImmnutableList class provides a function Builder(). Through this function, a new ImmutableList can be created, or
    an ImmutableList can be created from an existing List or both.

    • Creating a new ImmutableList




      // Java code illustrating of() method to
      // create a ImmutableList
      import java.util.*;
      import com.google.common.collect.ImmutableList;
        
      class GfG {
          public static void main(String args[])
          {
              // non-empty immutable set
              ImmutableList<String> iList = ImmutableList.<String>builder()
                                                .add("Geeks", "For", "Geeks")
                                                .build();
        
              // Let's print the List
              System.out.println(iList);
          }
      }
       
       

      Output:

        [Geeks, For, Geeks]  
    • Creating an ImmutableList from existing List




      // Java code illustrating of() method to
      // create a ImmutableList
      import java.util.*;
      import com.google.common.collect.ImmutableList;
        
      class GfG {
          public static void main(String args[])
          {
              // non-empty immutable set
              List<String> list = List.of("Geeks", "For", "Geeks");
              ImmutableList<String> iList = ImmutableList.<String>builder()
                                                .addAll(list)
                                                .build();
        
              // Let's print the List
              System.out.println(iList);
          }
      }
       
       

      Output:

        [Geeks, For, Geeks]  
    • Creating a new ImmutableList including the existing List




      // Java code illustrating of() method to
      // create a ImmutableList
      import java.util.*;
      import com.google.common.collect.ImmutableList;
        
      class GfG {
          public static void main(String args[])
          {
              // non-empty immutable set
              List<String> list = List.of("Geeks", "For", "Geeks");
              ImmutableList<String> iList = ImmutableList.<String>builder()
                                                .addAll(list)
                                                .add("Computer", "Portal", )
                                                .build();
        
              // Let's print the set
              System.out.println(iList);
          }
      }
       
       

      Output:

        [Geeks, For, Geeks, Computer, Portal]  


Try to change ImmutableList

As mentioned earlier, the below program will throw UnsupportedOperationException.




// Java code to show that UnsupportedOperationException
// will be thrown when ImmutableList is modified.
import java.util.*;
  
class GfG {
    public static void main(String args[])
    {
        // empty immutable map
        List<String> list = List.of();
  
        // Lets try adding element in  List
        List.add("Geeks");
    }
}
 
 

Output :

  Exception in thread "main" java.lang.UnsupportedOperationException      at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:218)      at ImmutableListDemo.main(Main.java:16)  

How is it different from Collections.unmodifiableList()?

Collections.unmodifiableList creates a wrapper around the same existing List such that the wrapper cannot be used to modify it. However we can still change original List.




// Java program to demonstrate that a List created using
// Collections.unmodifiableList() can be modified indirectly.
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>();
        list.add("Geeks");
  
        // Create ImmutableList from List using copyOf()
        List<String> iList = Collections.unmodifiableList(list);
  
        // We change List and the changes reflect in iList.
        list.add("For");
        list.add("Geeks");
  
        System.out.println(iList);
    }
}
 
 

Output:

  [Geeks, For, Geeks]  

If we create an ImmutableList from an existing List and change the existing List, the ImmutableList does not change because a copy is created.




// Below is a Java program for
// Creating an immutable List using copyOf()
// and modifying original List.
import java.io.*;
import java.util.*;
import com.google.common.collect.ImmutableList;
  
class GFG {
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>();
        list.add("Geeks");
  
        // Create ImmutableList from List using copyOf()
        ImmutableList<String> iList = ImmutableList.copyOf(list);
  
        // We change List and the changes wont reflect in iList.
        list.add("For");
        list.add("Geeks");
  
        System.out.println(iList);
    }
}
 
 

Output :

  [Geeks]  


Next Article
CopyOnWriteArrayList in Java

R

RishabhPrabhu
Improve
Article Tags :
  • Java
  • Java-Collections
  • java-guava
  • java-list
  • Java-List-Programs
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

  • Java List Interface
    The List Interface in Java extends the Collection Interface and is a part of the java.util package. It is used to store the ordered collections of elements. In a Java List, we can organize and manage the data sequentially. Key Features: Maintained the order of elements in which they are added.Allows
    15+ min read
  • AbstractList in Java with Examples
    The AbstractList class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. AbstractList class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a Rand
    8 min read
  • ArrayList in Java
    Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
    10 min read
  • LinkedList in Java
    Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and addr
    13 min read
  • Immutable List in Java
    ImmutableList, as suggested by the name, is a type of List which is immutable. It means that the content of the List are fixed or constant after declaration, that is, they are read-only. If any attempt made to add, delete and update elements in the List, UnsupportedOperationException is thrown. An I
    5 min read
  • CopyOnWriteArrayList in Java
    CopyOnWriteArrayList class is introduced in JDK 1.5, which implements the List interface. It is an enhanced version of ArrayList in which all modifications (add, set, remove, etc) are implemented by making a fresh copy. It is found in java.util.concurrent package. It is a data structure created to b
    6 min read
  • Custom ArrayList in Java
    Before proceeding further let us quickly revise the concept of the arrays and ArrayList quickly. So in java, we have seen arrays are linear data structures providing functionality to add elements in a continuous manner in memory address space whereas ArrayList is a class belonging to the Collection
    8 min read
  • Difference Between Synchronized ArrayList and CopyOnWriteArrayList in Java Collection
    As we know that the ArrayList is not synchronized, if multiple threads try to modify an ArrayList at the same time, then the final outcome will be non-deterministic. Hence synchronizing the ArrayList is a must to achieve thread safety in a multi-threaded environment. In order to make List objects we
    6 min read
  • How to remove a SubList from a List in Java
    Given a list in Java, the task is to remove all the elements in the sublist whose index is between fromIndex, inclusive, and toIndex, exclusive. The range of the index is defined by the user. Example: Input list = [1, 2, 3, 4, 5, 6, 7, 8], fromIndex = 2, endIndex = 4 Output [1, 2, 5, 6, 7, 8] Input
    2 min read
  • Randomly Select Items from a List in Java
    In this article, we will explore how to efficiently select an element from a list in Java. The basic approach involves generating a random index between 0 and the size of the list, and then using that index to retrieve the item. Different Ways to Select Items from a ListBelow are the different appro
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences