{"id":7267,"date":"2021-06-26T06:28:34","date_gmt":"2021-06-26T10:28:34","guid":{"rendered":"https:\/\/springframework.guru\/?p=7267"},"modified":"2021-09-10T08:45:58","modified_gmt":"2021-09-10T12:45:58","slug":"using-immutablelist-in-java","status":"publish","type":"post","link":"https:\/\/springframework.guru\/using-immutablelist-in-java\/","title":{"rendered":"Using ImmutableList in Java"},"content":{"rendered":"<p>There are read-only wrappers over collections which are known as <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">unmodifiable lists<\/code>. These lists do not support any modification operations such as add, remove, and clear. Hence, these kinds of lists which guarantee that no change in the Collection object will ever be visible are termed as immutablelist.<\/p>\n<p>The Java Collections framework provides the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">unmodifiableList()<\/code> method. It is not safe to use it as the returned list is only truly immutable if nobody holds a reference to the original collection. Therefore, Guava, a Java-based library developed by Google provides a simple, easy-to-use immutable version of each standard Collection type. It includes its own Collection variations. It also provides an instance of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableList<\/code> that contains its own private data and will never change.<\/p>\n<p>In this post, you will learn how to create and use <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableLists<\/code> in Java.<\/p>\n<h2>Features of ImmutableLists<\/h2>\n<ul>\n<li><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableLists<\/code>are read-only as the elements of the list are fixed or constant after declaration.<\/li>\n<li>An<code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">UnsupportedOperationException<\/code>gets thrown if you try to add, delete or update elements in the List.<\/li>\n<li>An<code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableList<\/code>does not allow null element. If any attempt is made to create an <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableList<\/code> with null element, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NullPointerException<\/code> is thrown.<\/li>\n<\/ul>\n<h2>Class hierarchy<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">java.lang.Object\r\n  \u21b3 java.util.AbstractCollection\r\n      \u21b3 com.google.common.collect.ImmutableCollection\r\n          \u21b3 com.google.common.collect.ImmutableList\r\n<\/pre>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">AbstractCollection<\/code> class provides a skeletal implementation of the Collection interface. It is extended by <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableCollection<\/code>, which is further extended by <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableList<\/code>.<\/p>\n<h2>Creating an ImmutableList<\/h2>\n<p>Immutable Lists can be created by the following methods.<\/p>\n<h2>ImmutableList using <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableList.of()<\/code> method<\/h2>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableList.of()<\/code> method returns an immutable list containing the given elements in order.<\/p>\n<p>This is the code for the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableList.of()<\/code> method.<\/p>\n<p><strong>ImmutableListDemo.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">import com.google.common.collect.ImmutableList;\r\n\r\nclass ImmutableListDemo {\r\n\r\n    public static void main(String[] args) {\r\n        ImmutableList immutableList =\r\n                ImmutableList.of(\"Immutable\", \"Lists\", \"Java\");\r\n        System.out.println(immutableList);\r\n }\r\n}\r\n<\/pre>\n<p>The output on running the code in IntelliJ is this.<br \/>\n<a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-7288\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable1.png\" alt=\"OfMethod\" width=\"780\" height=\"148\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable1.png 780w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable1-300x57.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable1-768x146.png 768w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable1-410x78.png 410w\" sizes=\"(max-width: 780px) 100vw, 780px\" \/><\/a><\/p>\n<h2>ImmutableList using <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableList.copyOf()<\/code> method<\/h2>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableList.copyOf()<\/code> method returns an immutable list containing the elements of the specified list. It returns a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NullPointerException<\/code> if any of the elements is null.<\/p>\n<p>The code for <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableList.copyOf()<\/code> method is this.<\/p>\n<p><strong>ImmutableListDemo.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">import com.google.common.collect.ImmutableList;\r\nimport java.util.*;\r\n\r\nclass ImmutableListDemo {\r\n\r\n    public static void main(String[] args) {\r\n        List list = new ArrayList&lt;&gt;(Arrays.asList(\"Using\", \"CopyOf\", \"Method\"));\r\n        ImmutableList immutableList1 = ImmutableList.copyOf(list);\r\n        List list1 = new ArrayList&lt;&gt;(Arrays.asList(\"Using\", \"CopyOf\", \"Method\", null));\r\n        ImmutableList immutableList2 = ImmutableList.copyOf(list1);\r\n        System.out.println(\"ImmutableList using copyOf() method\" + \":\" + immutableList1);\r\n        System.out.println(\"ImmutableList to insert null element\" + \":\" + immutableList2);\r\n }\r\n}\r\n<\/pre>\n<p>In line 9, you are using the copyOf() method to create immutableList1. In line 10, you are trying to add null element to the same list, which results in <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">NullPointerException<\/code>.<\/p>\n<p>This is the output on running the code in IntelliJ.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/copyofList.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-7309\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/copyofList.png\" alt=\"using copyOf method\" width=\"620\" height=\"152\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/copyofList.png 620w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/copyofList-300x74.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/copyofList-410x101.png 410w\" sizes=\"(max-width: 620px) 100vw, 620px\" \/><\/a><\/p>\n<p>And this is the output of when you try to add a null element to an immutable list.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/nullpointerlist.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-7310\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/nullpointerlist.png\" alt=\"\" width=\"830\" height=\"243\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/nullpointerlist.png 830w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/nullpointerlist-300x88.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/nullpointerlist-768x225.png 768w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/nullpointerlist-410x120.png 410w\" sizes=\"(max-width: 830px) 100vw, 830px\" \/><\/a><\/p>\n<h2>ImmutableList using <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Builder()<\/code> method<\/h2>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Builder()<\/code> function helps to create a new ImmutableList or creates from an existing List.<\/p>\n<p>Here is the code.<\/p>\n<p><strong>ImmutableListDemo.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">import com.google.common.collect.ImmutableList;\r\n\r\nclass ImmutableListDemo {\r\n\r\n    public static void main(String[] args) {\r\n ImmutableList iList = ImmutableList.builder()\r\n                .add(\"using\", \"builder\", \"method\")\r\n                .build();\r\n        \r\n        System.out.println(iList);\r\n }\r\n}\r\n<\/pre>\n<p>Here is the output for the preceding code.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable4.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-7293\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable4.png\" alt=\"builderMethod\" width=\"687\" height=\"156\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable4.png 687w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable4-300x68.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable4-410x93.png 410w\" sizes=\"(max-width: 687px) 100vw, 687px\" \/><\/a><\/p>\n<h2>ImmutableList using Java 9 \u2013 Collection factory methods<\/h2>\n<p>The collection factory methods are only available for List, Set, and Map interfaces. The returned collection is structurally immutable, i.e., we cannot add elements, removed or replaced them from the collection.<\/p>\n<p>This is the code for creating an immutable list using collection factory methods.<\/p>\n<p><strong>ImmutableListDemo.java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">import java.util.*;\r\n\r\nclass ImmutableListDemo {\r\n\r\n    public static void main(String[] args) {\r\n        List immutableList2 = List.of(\"Using\", \"Java9\", \"factory\", \"method\");\r\n        System.out.println(immutableList2);\r\n        immutableList2.add(\"ExceptionDemo\");\r\n        System.out.println(immutableList2);\r\n }\r\n}\r\n<\/pre>\n<p>The output on running the code in IntelliJ is this.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-7290\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable3.png\" alt=\"factoryMethod\" width=\"973\" height=\"239\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable3.png 973w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable3-300x74.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable3-768x189.png 768w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable3-848x208.png 848w, https:\/\/springframework.guru\/wp-content\/uploads\/2021\/06\/immutable3-410x101.png 410w\" sizes=\"(max-width: 973px) 100vw, 973px\" \/><\/a><\/p>\n<p>Any modification operation will throw an <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">UnsupportedOperationException<\/code> as we tried to add <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ExceptionDemo<\/code> to the already created <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ImmutableList<\/code>.<\/p>\n<h2>Summary<\/h2>\n<p>It is clearly evident that you can create an unmodifiable List out of an existing <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ArrayList<\/code> using either the core JDK, Google Guava, or Apache Commons Collections. Also <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Collections.unmodifiableList<\/code> 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.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>There are read-only wrappers over collections which are known as unmodifiable lists. These lists do not support any modification operations such as add, remove, and clear. Hence, these kinds of lists which guarantee that no change in the Collection object will ever be visible are termed as immutablelist. The Java Collections framework provides the unmodifiableList() [&hellip;]<a href=\"https:\/\/springframework.guru\/using-immutablelist-in-java\/\" class=\"df-link-excerpt\">Continue reading<\/a><\/p>\n","protected":false},"author":111,"featured_media":4592,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[20],"tags":[362,363,27],"class_list":["post-7267","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-collections","tag-immutable-lists","tag-java"],"jetpack_publicize_connections":[],"aioseo_notices":[],"modified_by":"jt","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/springframework.guru\/wp-content\/uploads\/2015\/03\/Banner560x292_07web.jpg","jetpack_shortlink":"https:\/\/wp.me\/p5BZrZ-1Td","_links":{"self":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/7267"}],"collection":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/users\/111"}],"replies":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/comments?post=7267"}],"version-history":[{"count":26,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/7267\/revisions"}],"predecessor-version":[{"id":7600,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/7267\/revisions\/7600"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media\/4592"}],"wp:attachment":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media?parent=7267"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/categories?post=7267"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/tags?post=7267"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}