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:
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?)
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!!!
Interesting. Thanks for the info!
Post a Comment