Concise code with Generics and varargs

Tags:

http://www.theserverside.com/blogs/thread.tss?thread_id=37839

How to create collections with initial items.

(1) Generics + New method (viz. CollectionUtils.newList)

So code that looked like this before:

List<String> programmingLanguages = new ArrayList<String>(3);
programmingLanguages.add(“Java”);
programmingLanguages.add(“C++”);
programmingLanguages.add(“Ruby”);

Now looks like this:

List<String> programmingLanguages = CollectionUtils.newList(
   “Java”, “C++”, “Ruby”);

(2) Anonymous class

I’ve been using this more and more to quickly initialize data structures in-place:

Map<String, String> langs = new HashMap<String, String>(3) {{
   put(“Java”, “Wicked”);
   put(“C++”, “Ok”);
   put(“Ruby”, “Interesting”);
}};

Comments

One response to “Concise code with Generics and varargs”

Leave a Reply

Your email address will not be published. Required fields are marked *