Can I add elements to a java.util.List that is backed by an array?

It seems that you can add elements to a java.util.List that is backed by an array. For example, you could try this:

import java.util.Arrays;
import java.util.List;

public class ListSample {
    public static void main(String[] args) {
String[] a = {“foo”, “bar”};
List l = Arrays.asList(a);
l.add(“baz”);
System.out.println(l.get(0));
System.out.println(l.get(1));
    }
}

This compiles just fine (OpenJDK 1.7 on openSUSE). However, if you run the sample, an exception will be thrown.
 
neifer@linux-asb4:~/tmp> javac ListSample.java
neifer@linux-asb4:~/tmp> java ListSample
Exception in thread “main” java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at ListSample.main(ListSample.java:8)
neifer@linux-asb4:~/tmp> 
Read the API documentation for List.add() and you will find out that it is an optional operation not all implementations provide and that it might throw an UnsupportedOperationException.
Advertisements
Can I add elements to a java.util.List that is backed by an array?

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