# Collection-like classes in Java - taking advantage of varargs

I quite often need to implement collection-like classes and - to make using them more comfortable - would like to take advantage of a constructor with variable arguments.

The following implementation does not work, though.

class FruitsStore
{
private List<String> availableFruits;

public FruitsStore(String... fruits)
{
this.availableFruits = Arrays.asList(fruits);
}

{
}

...
}


The following code snippet

FruitsStore store = new FruitsStore("banana", "melon");


throws the following exception

Exception in thread "main" java.lang.UnsupportedOperationException
at cz.dusanrychnovsky.FruitsStore.main(FruitsStore.java:12)


To overcome this issue, I use a constructor like this:

public FruitsStore(String... fruits)
{
}


This compiles and works fine.

Is this a good coding practice? Does it have any drawbacks? What implementation would you suggest?

-
docs.oracle.com/javase/6/docs/api/java/util/… returns a fixed-size list. No add no remove. –  abuzittin gillifirca Dec 31 '12 at 14:35
But what is the correct way to get around this issue? –  Dušan Rychnovský Dec 31 '12 at 14:53
I don't see why you would need to define a new class just to represent a (crippled) collection of objects and do nothing else with it when you could just use a plain list assigned to an appropriately named variable. What you've shown here doesn't justify the need. –  Jeff Mercado Jan 1 '13 at 11:03
The code was only meant to illustrate the problem. The classes always contain other (domain specific) methods to operate on the list, which are not provided by any standard collection classes. I edited the post to make this more obvious (three dots at the end of the class definition). –  Dušan Rychnovský Jan 1 '13 at 12:23

You have found the natural solution to this situation. Arrays.asList will give you a List with specific features - new xxList(Arrays.asList(...)) will give you a list with attributes you require.