The situation you are describing will be quite rare: in most cases your varargs elements will be String s, or numbers, or Widget s ... it will be unusual for them to be Object (this can be anything) or arrays.
But if the varargs argument has a bunch of Object or an array type, then your question arises: you can pass one array to it, and then how does the compiler know if you mean to pass an array (the one you provided) or a series of 1 element that should it insert into an array for you?
A quick test shows the answer:
public class TestClass { public static void main(String[] args) { Object anObject = new Object(); Object[] anArray = new Object[] {anObject, anObject}; System.out.println("object1 = " + anObject); System.out.println("array1 = " + anArray); takesArgs(); takesArgs(anObject, anObject); takesArgs(anArray);
The result of the execution (your exact numbers will vary:
object1 = java.lang.Object@3e25a5 array1 = [Ljava.lang.Object;@19821f The array was [Ljava.lang.Object;@addbf1 The array was [Ljava.lang.Object;@42e816 The array was [Ljava.lang.Object;@19821f The array was [Ljava.lang.Object;@9304b1
Thus, the answer is that in ambiguous cases, it considers what you passed as an array, instead of creating a new array to transfer it. This makes sense, as you can always wrap it in an array yourself if you want a different interpretation.
mcherm Nov 03 '09 at 1:27 2009-11-03 01:27
source share