Object Partners

How many times do you find yourself creating this code over and over again in tests or even production code? List<String> stringList = new ArrayList<String>(); stringList.add("some test string"); stringList.add("some other test string"); aMethodThatTakesAListOfStrings(stringList); Rather than writing this same code over and over again, there is an easier way to create a simple generic list of objects in one method. The following method makes use of two Java 5 features: variable list arguments and generics. Here’s what it looks like: public static <E> List<E> createArrayList(final E... values) { final List<E> list = new ArrayList<E>(values.length); for (final E value : values) { list.add(value); } return list; } Let me break down what’s happening here.

public static <E> List<E> this creates a static method and declaring E as a generic type that this method will use and returns a list of that type.

createArrayList(final E... values) Here a variable length argument array of any type is passed in and “E” is typed to what is passed in. For example if String were passed in, E would be then typed to an array of String, or if BigDecimal were passed in, E would be typed to an array of BigDecimal (The JVM treats variable length arguments as arrays).   Anywhere there is an E, this gets typed to whatever is passed in.

In the rest of the method, an ArrayList of E is created and then the array is looped over and each type is added to the list and the list is then returned.  Here’s the same code as above using our new method:

aMethodThatTakesAListOfStrings(createArrayList("some test string", "some other test string"));

Much nicer isn’t it? That can be used with any object too such as:

aMethodThatTakesAListOfIntegers(createArrayList(1, 2, 3));

The same can be done with any other collection type such as Set, SortedSet, etc. and makes testing and writing code much eaiser.

Share this Post

Related Blog Posts

Unknown

Object Partners, Inc. approach with agile methodology

April 16th, 2009

What brought us to Agile? The most common software management technique in the past and today is called “waterfall” Software Development. As defined by Wikipedia, the definition for Waterfall development is a sequential development process, in which…

Ehren Seim
Unknown

How to write a Technical Resume

March 13th, 2009

There are a lot of different ideas, questions, and discussions going around about resumes and cover letters, so I thought I’d jump in the mix. I’ve seen literally tens of thousands of resumes in my day, some terrible, some great. But all are…

Object Partners
Unknown

Another Failure To Use Code Coverage Numbers Correctly

February 23rd, 2009

I’ve been approached recently by members of various projects about how to improve code coverage numbers. In an abuse of the numbers or a misunderstanding of their purpose, there’s mandates to keep code coverage at 80%. Other team’s have been closer…

Object Partners

About the author