Java SE 9: Factory Methods for Immutable List

Filed Under: Java

Post Brief Table of Content:

  • Introduction
  • Java SE 8: Empty Immutable List
  • Java SE 9: Empty Immutable List
  • Java SE 8: Non-Empty Immutable List
  • Java SE 9: Non-Empty Immutable List
  • Characteristics of Immutable List

Introduction

Oracle Corporation is going to release Java New Version: Java SE 9 around March 2017. So, I would like to deliver a series of Posts on Java SE 9 New Features. It is my forth post in this series.

I have already delivered couple of posts on Java SE 9 New Features. Before going through this posts, please read them below :

In this post, we are going to discuss one more Java SE 9 New Feature: “Factory Methods for Immutable List” with some simple and suitable examples.

Java SE 8: Empty Immutable List

In Java SE 8 and earlier Versions, if we want to create an empty Immutable or Unmodifiable List, we should use Collections class utility method: unmodifiableList as shown below:

Example:-


 List<String> emptyList = new ArrayList<>();
 List<String> immutableList = Collections.unmodifiableList(emptyList);

NOTE:- Diamond Operator does NOT work in Java SE 6 and earlier versions. Rest of the code is same for all Java versions.

Test the above code in Java SE 9 REPL:

unmodified_empty_list

Here we can observe that to create an empty Immutable List, we need to do lot of stuff as shown above. It is very tedious and verbose thing right. Let us see the same thing in Java SE 9 now.

NOTE:- For simplicity and quick testing purpose, I’m using Java SE 9 REPL (JShell). That’s why we need an REPL for each language to test new feature quickly without doing much work.

Java SE 9: Empty Immutable List

To overcome those shortcomings, Java SE 9 has introduced a couple of useful methods in List interface so that we do not need to use all these tedious steps to create Immutable Empty List.

If we go through the Java SE 9 List API, we can find the below method signature in List interface.


 static <E> List<E> of()

It is used to create an empty Immutable List (a List with zero elements).

Example:-


 List<String> immutableList = List.of();

Test the above code in Java SE 9 REPL:

new_unmodified_empty_list

Here we can observe that it is very easy to create an empty Immutable List in Java SE 9.

Java SE 8: Non-Empty Immutable List

Now we will see how to create Non-Empty Immutable List in Java SE 8 and earlier versions.

Example:-


 List<String> list = new ArrayList<>();
 list.add("one");
 list.add("two");
 list.add("three");
 List<String> immutableList = Collections.unmodifiableList(list);

Here also we can observe that to create a non-empty Immutable List, we need to do lot of stuff and very tedious and verbose steps. Let us see the same thing in Java SE 9 now.

Java SE 9: Non-Empty Immutable List

To overcome those shortcomings, Java SE 9 has introduced the following useful overloaded methods.

These useful methods are used to create a new Immutable List with one element to 10 elements:


static <E> List<E> of(E e1)
static <E> List<E> of(E e1,E e2)	
static <E> List<E> of(E e1,E e2,E e3)
static <E> List<E> of(E e1,E e2,E e3,E e4)
static <E> List<E> of(E e1,E e2,E e3,E e4,E e5)	
static <E> List<E> of(E e1,E e2,E e3,E e4,E e5,E e6)	
static <E> List<E> of(E e1,E e2,E e3,E e4,E e5,E e6,E e7)	
static <E> List<E> of(E e1,E e2,E e3,E e4,E e5,E e6,E e7,E e8)	
static <E> List<E> of(E e1,E e2,E e3,E e4,E e5,E e6,E e7,E e8,E e9)	
static <E> List<E> of(E e1,E e2,E e3,E e4,E e5,E e6,E e7,E e8,E e9,E e10)

The following is a Var-Args method (Variable Number of arguments method):


static <E> List<E> of(E... elements)  

Example:-


 List<String> immutableList = List.of("one","two","three");

It is very simple and no-verbosity in this code right. Very nice stuff!

Test the above code in Java SE 9 REPL:


jshell> List<String> immutableList = List.of("one","two","three")
immutableList ==> [one, two, three]

Characteristics of Immutable List

As we know, Immutable Lists are not modifiable (unmodifiable collections). In this section, we will discuss the Characteristics of Immutable List(They are same in all Java versions.):

  • They are Immutable.
  • We cannot add, modify and delete their elements.
  • If we try to perform Add/Delete/Update operations on them, we will get UnsupportedOperationException as shown below:
  • 
    jshell> immutableList.add("four")
    |  java.lang.UnsupportedOperationException thrown: 
    |        at ImmutableCollections.uoe (ImmutableCollections.java:68)
    |        at ImmutableCollections$AbstractImmutableList.add (ImmutableCollections.java:74)
    |        at (#2:1)
    
  • They don’t allow null elements.
  • If we try to create them with null elements, we will get NullPointerException as shown below:
  • 
    jshell> List>String> immutableList = List.of("one","two","three", null)
    |  java.lang.NullPointerException thrown: 
    |        at Objects.requireNonNull (Objects.java:221)
    |        at ImmutableCollections$ListN. (ImmutableCollections.java:179)
    |        at List.of (List.java:859)
    |        at (#4:1)
    
  • If we try add null elements, we will get UnsupportedOperationException as shown below:
  • 
    jshell> immutableList.add(null)
    |  java.lang.UnsupportedOperationException thrown: 
    |        at ImmutableCollections.uoe (ImmutableCollections.java:68)
    |        at ImmutableCollections$AbstractImmutableList.add (ImmutableCollections.java:74)
    |        at (#3:1)
    
  • They are serializable if all elements are serializable.

That’s it all about “Java SE 9: Factory Methods for Immutable List” concept. We will discuss some more Java SE 9 New Features in my coming posts.

Please drop me a comment if you like my post or have any issues/suggestions/type errors.

Thank you for reading my tutorials.

Happy Java SE 9 Learning!

Comments

  1. Sswapnil says:

    Java 9 List.Of() methods are complex and unconvicing. They could have retained the earlier Immutables methods and just given us short methods like list.umodOf()? but its use is limited as they cannot be added/del/updated.

    Array list(list.Of()); is the only use relevant to it. Even passing this Immutable as a Command or DTO to consumers would break the protocol.

    Oracle could relook it and try to fix in Java 10.

  2. Peter Ivarsson says:

    List immutableList = List.of();

    What are the meaning with an empty Immutable List?

    If “We cannot add, modify and delete their elements”.

  3. RevanthKrishnaKumar V. says:

    Is there any practical application/use case when we create empty immutable list / map.. It is unchangeable and obviously empty then why we need this.?

  4. Sarath says:

    Hi ,

    Can a unmodifiableList can contain modifiable objects?
    Say unmodfiableList has 4 students. Is it possible o update/modify these student objects. Or these object should also be non modifiable ??

    please clarify.

    1. Pankaj says:

      Unmodifiable List takes care of structural changes in the list, but you can certainly modify it’s elements. For example, change the student name through setter methods will have no issues because it’s not altering the list structure. However if you will try to delete an element, it will throw exception.

  5. Antioch Sanders says:

    Hey I’m seeing this and I’m super confused. Why would they make List.of() return an immutable list??? I was assuming the of methods were to ease initialization – we don’t have to do a bunch of list.add() operations. But if the lists are immutable, we lose the advantage we had over arrays, namely making size changes to them with add() and remove().
    .
    The only useful thing I see here is that we can now do “new ArrayList(List.of(1, 2, 3, 4));” for initialization. Yet this seems awkward – couldn’t they just add new constructors for ArrayList, LinkedList etc. which ease initialization? Then we would have, “new ArrayList(1, 2, 3, 4)”.
    .
    Additionally, this new of() scheme doesn’t allow us to easily get immutable copies of lists, which has been the only cause for an immutable list method that I’ve ever had (making sure that some code doesn’t change a list). If they truly wanted to save characters in writing Collections.unmodifiableList(List list) (used twice in the JDK), why not have a list method that goes like, “list.unmodifiable()”, which returns a clone of sorts?
    Source about JDK usage: http://wiki.c2.com/?UnmodifiableListIsStupidAndItBreaksLsp
    .
    The last issue I had with the docs were the inclusion of 10 versions of “List.of()”. Shouldn’t List.of(E… elements) deal with all of those? The other methods just seem to clog up the javadocs…
    .
    Anyways, any direction on why Oracle has chosen this direction with the various unmodifiable collections would be really helpful for me.
    .
    Thanks, Anti

    1. Rambabu says:

      I too have same questions. But all these are not for me. We should ask them to Java SE 9 API developers of Oracle Corp.
      I think they should have some major reason to design APIs in such a way.

      Ram

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages