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);
}
public void add(String fruit)
{
this.availableFruits.add(fruit);
}
...
}
The following code snippet
FruitsStore store = new FruitsStore("banana", "melon");
store.add("orange");
throws the following exception
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at cz.dusanrychnovsky.FruitsStore.add(FruitsStore.java:26)
at cz.dusanrychnovsky.FruitsStore.main(FruitsStore.java:12)
To overcome this issue, I use a constructor like this:
public FruitsStore(String... fruits)
{
this.availableFruits = new LinkedList<String>(Arrays.asList(fruits));
}
This compiles and works fine.
Is this a good coding practice? Does it have any drawbacks? What implementation would you suggest?
addnoremove. – abuzittin gillifirca Dec 31 '12 at 14:35