Saturday, July 11, 2009

Viral Patel gave a short discussion on his blog entitled Convert ArrayList to Arrays in Java. This is a good thing to know how to do but he did not cover the reverse operation, converting arrays to lists. It holds a few surprises for you. So here is a short snippet that demonstrates this opposite operation.

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

public class ArraysAsList {
public statis void main(String[] args) {
new ArraysAsList().start();
}

private void start() {
String[] countries = {"India", "Switzerland", "Italy", "France"};
List list = Arrays.asList(countries);
list.add("India");
}
}

If we run this small program we get.....
WHAT!!!! an exception?!?!?!What going on here? All we wanted to do was add an element to the generated array. Here's the exception:

java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:131)

Whaddaya mean unsupported operation? Let's look at the javadoc and see what it says:

"Returns a fixed-size list backed by the specified array."
Aha! there's the problem. That means that I can't remove anything either. Try it.
Don't forget this in your coding, it can bite you. Not a big deal but just what you need to deal with when you're under the pressure of a deadline.

Thanks to Damien for reminding me to show you the correct way to do this:
List list = Arrays.asList(countries);
should be:
List list = new ArrayList(Arrays.asList(countries));
This fixes the problem. Now you can add, delete, whatever.

1 comment:

damien said...

The Arrays.asList method is just a utility function. To use it properly, you'd need to change
List list = Arrays.asList(countries);
in your code to
List list = new ArrayList(Arrays.asList(countries));

Good thing to bring to the attention of alot of people who might not know that!