or

Varargs Collection Factory Method

If you read my double brace post, you might find it very handy. However, sometimes you might be warned by PMD or Checkstyle for this kind of usage. Because they don’t like this kind of usages. One way to fix this problem is putting either //no pmd or suppressing method for PMD.NonStaticInitializer.

In this post, I wanna talk about; Varargs which came with Java 5, and how can find a solution to our problem by using varargs.

What is Varargs?

The variable arguments, aka Varargs is a new feature that is introduced in Java 5. The idea was allowing user to pass more than one same type argument to a method by using only one syntax. So instead of sending an array of objects, now we’re sending a number of objects and Java makes them an array implicitly. They syntax and use like:

public void doSomething(String... myStringArgs) {
   for (String stringArg : myStringArgs) {
      // do something
   }
}

// and call would be like

doSomething("arg1", "arg2");
// or
doSomething("arg1", "arg2", "arg3", "arg4", "arg5");

Creating a Collection Factory

As I previously explained in double brace post, Java really doesn’t have a literal syntax for collections. So this makes creating collections a bit harder. We can overcome this problem by applying double brace initialization. However, for PMD and Checkstyle sake, we might think creating a Varargs Collection Factory Method. Please look at the following code:

Set<String> cars = new HashSet<String>();

cars.add("BMW");
cars.add("Mercedes");
cars.add("Ford");

doSomething(cars);

// instead of using above usage

public Set<String> setOf(String... items) {
   return new HashSet<String>(Arrays.asList(items));
}

doSomething(setOf("BMW", "Mercedes", "Ford"));

I personally find above usage very handy too, especially if you create your collection factory method with generics.



One Response

  1. Esat Postaci

    Hi Isa,

    I measured that setOf method with 2346 arguments and no performance changes occured.

    I realized that the compiler recognizes the these arguments of the “setOf” method as new String[] { … } Best Regards

    June 17, 2009, 11:02 PM

Leave a Reply

Name (required)
Mail (required)
Website