Sometimes the one-line urge gets the best of me:
someMethodCall(new ArrayList<String>(2) { { add("foo"); add("bar"); } });
Yes! It is the infamous anonymous instance initializer block. I suppose it would not have killed me to type instead:
final List<String> listy = new ArrayList<String>(2); listy.add("foo"); listy.add("bar"); someMethodCall(listy);
But the one-liner was so much more fun to format with my editor. This is what pair programming is good for, to stop non-sense like that. When you have a peer watching you type, you are too embarrassed to commit unmaintainable code into the codebase.
UPDATE: Looking of the documentation for java.util.Arrays.asList(T... a)
made me realize an even easier way to get the one-liner, and a maintainble one at that:
someMethodCall(Arrays.asList("foo", "bar"));
How slick!
1 comment:
asList is old. Using variadic args (...) is new with 1.5. Nice application of the syntax.
Post a Comment