Sunday, October 28, 2018

Do you know - Series - 3: Arrays as List: Java

Mose of the time we use the method Arrays.asList(T… a) to covert an array into a List. But, what we forget is that the returned list is not modifiable. It will be a fixed list backed up by the given array of elements.

This fixed list won't stop you using the method add(), to add an element to the list and remove(), to remove an element at a particular index, but will throw UnSupportedOperationException at runtime.

If you look at the Arrays class it has its own implementation of ArrayList and that is what returned by the asList() method. Though the ArrayList class extends the AbstractList, but does not override the add() and remove() methods which is actually the reason for the UnSupportedOperationException.

So, the use of Arrays.asList(T… a) is to just get an readonly List from an array of elements. It just acts a bridge between array and collection based APIs.

If you need a modifiable List then you may wrap this unmodifiable list into an ArrayList as given in the below sample code.

public List getList(String[] array) {
    List unModifiableList = Arrays.asList(array);
    unModifiableList.add("abc"); //not supported
    unModifiableList.remove(1); //not supported
    List modifiableList = new ArrayList(unModifiableList); //wrapper to read-only list
    modifiableList.add("abc"); //supported
    modifiableList.remove(1);  //supported

No comments:

Post a Comment

Do you know - Series - 4: Boxing and Unboxing - Integer assignment and comparison

We know about boxing and unboxing in Java. It is about automatic conversion of primitive type value into its Wrapper Object equivalent type...