Inside Java: Arrays.asList(T… a)

We frequently use asList method of Arrays class to convert an array to a list. In order to use this method properly we need to know what is happening behind the scene. The complete signature of this method is:   

      public static <T> List<T> asList(T... a)
 

This method is declared and defined in java.util.Arrays class. The method returns an object of ArrayList class. But here is one difference which we have to note and take care while using this.     

The object being returned does not belong to java.util.ArrayList class rather it belongs to java.util.Arrays$ArrayList class. Surprised! Actually the Arrays class defines an private static inner class named ArrayList. Following is the signature of the ArrayList class:     

      private static class ArrayList<E> extends AbstractList<E>implements RandomAccess, 
      java.io.Serializable 

 

Now let us see what the difference between the two ArrayList classes is.  

The Arrays$ArrayList class is sometimes refered as the view of java.util.ArrayList or a fixed size list. This class does not override all the methods of AbstractList class. To be more precise, following are the methods it overrides or declares:     

      public int size()  

      public Object[] toArray()

      public <T> T[] toArray(T[] a)

      public E get(int index)

      public E set(int index, E element)

      public int indexOf(Object o)

      public boolean contains(Object o)

 

Other methods if being called refer to the AbstractList class default implementation.  

For example if we try to call the add or remove method of Arrays$ArrayList class, we will get an UnsupportedOperationException . The reason behind this is the implementation of these methods in the AbstractList class which is:  

      public void add(int index, E element) {
                 throw new UnsupportedOperationException();
      }  

      public E remove(int  index) {
                 throw new  UnsupportedOperationException();
      }  

 

I hope this clears the understanding of how views are being used in java.

Let us conclude this article with the javadoc comments of Arrays.asList method: 

Returns a fixed-size list backed by the specified array.  (Changes to the returned list “write through” to the array.)  This method acts as bridge between array-based and collection-based APIs, in combination with Collection#toArray.  The returned list is serializable and implements RandomAccess.

This method also provides a convenient way to create a fixed-size list initialized to contain several elements:
List<String> stooges = Arrays.asList(“Larry”, “Moe”, “Curly”);
 

Enjoy Learning,
Kamlesh

Advertisements

11 thoughts on “Inside Java: Arrays.asList(T… a)

  1. Thanks Kamlesh for this info. I faced this problem and was wondering why am I not able to add or remove elements from this arraylist.

  2. Good point – but I am wondering why did the Java Team decide to implement it this way. Why did they not use the ArrayList as is available and why did they try to create and use the nested ArrayList class inside Arrays.

    • Thanks Sumit!
      Few more thoughts about asList method: This method is actually a wrapper over a trivial java array. The returned list is not an ArrayList because it is a fixed size list (resembling the characteristics of an array). The use case for introducing this method is for using the array as list in APIs. There are few other classes also which are actually the wrapper over some Collection class. These classes are known as views. For more information see the methods of java.util.Collections class.
      http://java.sun.com/javase/6/docs/api/java/util/Collections.html

  3. Thanks for this excellent write-up. I just ran into one of these “quasi-Lists” being handed to me and now I know why it got that way.

    Seems like an absolutely horrible idea on sun/oracle’s part though…so if i get a list from some external chunk of code, i should copy it to a real list or else risk unexpected exceptions downstream in my system? Yeah, who thought this was a good idea? 🙂

    Scott

  4. Pingback: Arrays.asList(T… a) 살펴보기 « turtle9
    • Thanks Symbile,
      This is a very good question. The statement means that albeit the list returned by Arrays.asList method does not allow structural changes, the
      public E set(int index, E element)
      method can be used to update the any existing element of the list and the same will be reflected to the original array as well.

      Please refer the below code snippet which illustrates the same:

      public class TestArraysAsList {
      public static void main(String[] args) {
      String[] arr = new String[]{“A”, “B”, “C”, “D”};
      List list = Arrays.asList(arr);
      //list.add(“E”); // throws java.lang.UnsupportedOperationException
      list.set(1, “B1”);
      System.out.println(list.get(1)); //Output: B1
      System.out.println(arr[1]); //Output: B1
      }
      }

      – Kamlesh

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s