varargs and the '...' argument

Martijn Courteaux picture Martijn Courteaux · Nov 1, 2009 · Viewed 44k times · Source

Consider the method declaration:

String.format(String, Object ...)

The Object ... argument is just a reference to an array of Objects. Is there a way to use this method with a reference to an actual Object array? If I pass in an Object array to the ... argument - will the resultant argument value be a two-dimensional array - because an Object[] is itself an Object:

Object[] params = ....; // Make the array (for example based on user-input)
String s = String.format("%S has %.2f euros", params);

So the first component of the array (Which is used in the String.format method), will be an array and he will generate:

[class.getName() + "@" + Integer.toHexString(hashCode())] 

and then an error because the array size is 1.

The bold sequence is the real question.
This is a second question: Does a ... array/parameter have a name?

Answer

Ayman Hourieh picture Ayman Hourieh · Nov 1, 2009

From the docs on varargs:

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

So you can pass multiple arguments or an array.

The following works just fine:

class VarargTest {
  public static void main(String[] args) {
    Object[] params = {"x", 1.2345f};
    String s = String.format("%s is %.2f", params);
    System.out.println(s); // Output is: x is 1.23
  }
}