Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java varargs support collections?

In my Java code I often use the very handy method(Class... args) varargs. As far as I know, they allow you to pass any amount of Class objects or an array of Class[]. Since I also often use the Java collection classes, I am frustrated by the lack of compatibility between both. As a result, I end up doing collection.toArray(), but that has some type safety issues.

So now for the question: why doesn't Java allow instances of Iterable<T> as vararg arguments, as long as the generic type fits the T... type of the vararg? Doesn't everyone use lists, sets, etc. all the time? Is there an easy, type-safe way to provide the conversion from collection to vararg?

like image 801
tb189 Avatar asked Aug 01 '11 12:08

tb189


People also ask

Is it good to use varargs in Java?

Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String. format . The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.

What is the rule for using varargs in Java?

Rules to follow while using varargs in JavaWe can have only one variable argument per method. If you try to use more than one variable arguments a compile time error is generated.

Can Varargs be used in abstract method?

A method with a varargs annotation produces a forwarder method with the same signature (args: Array[String])Unit as an existing method. And of course putting the annotation only on the bar in Baz means we can't use the forwarder from a Bar instance.

How many values can be accommodated by Varargs in Java?

There is no limit. There can be any number of methods or constructors with one Vararg per each method or constructor.


1 Answers

The reason is simple: a variable arity parameter is simply an old-school array paramater with some additional metadata that tells the compiler to provide some syntactic sugar (namely, it allows implicit array creation).

So from the perspective of the JVM Object... is pretty much the same as Object[]. Allowing collections as well would require a more invasive change to the JVM (which has no explicit support for collections to date).

Note that if you want to support both ways, then making the collection-based method is probably the better approach:

public void frobnicate(Object... args) {   frobnicate(Arrays.asList(args)); }  public void frobnicate(Iterable<Object> args) {   // do stuff } 

The reason for this is that using Arrays.asList() is usually a cheaper operation than Collection.toArray() (because it creates a simple wrapper).

like image 95
Joachim Sauer Avatar answered Oct 09 '22 11:10

Joachim Sauer