Thursday, September 3, 2009

Nifty little Java trick...

In Java, there are many times when you have to deal with collections.  The code that is required in order to build a collection can be pretty cumbersome and usually follows the following pattern:

List strList = new ArrayList;
strList.add("1");
strList.add("2");
strList.add("3");

This code above can easily be changed to one line of code as such:
List strList = Arrays.asList("1", "2", "3");

I have found this little trick especially useful when writing unit tests.

If you plan on using this test in production level code, then you should be aware that creating a list in this fashion, does not allow for editing the list later. Instead, you should wrap the newly formed list in a constructor like so:
List strList = new ArrayList(Arrays.asList("1", "2", "3"));

Enjoy...

3 comments:

Jon Schneider said...

Just out of curiosity, why can't you add to the list generated by the 2nd snippet? Do you get some underlying type back that doesn't support the List.add() method? (If so, again out of curiosity, what type is it?)

Carlus Henry said...

Jon,

Pretty silly reason...but if you look at javadocs for the List interface, you will see that the add method is an optional operation.

Regarding the type of list that is returned...just wrote a quick little test, and it seems to be an inner class of the Arrays object, which implements the AbstarctList which does not implement the add method, but instead throws a nice UnsupportedOperationException for trying ;)

Pay it forward!!!

Jon Schneider said...

Interesting. Thanks for the info!