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...