Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

varargs and the '...' argument

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?

like image 527
Martijn Courteaux Avatar asked Nov 01 '09 11:11

Martijn Courteaux


People also ask

What are variable arguments or Varargs?

Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.

What is the rule for using Varargs?

Rules for varargs:There can be only one variable argument in the method. Variable argument (varargs) must be the last argument.

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 Varray variable argument )?

Variable argument or varargs in Java allows you to write more flexible methods which can accept as many arguments as you need. variable arguments or varargs were added in Java 1.5 along with great language features like Java Enum, Generics, autoboxing and various others.


1 Answers

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   } } 
like image 101
Ayman Hourieh Avatar answered Oct 02 '22 19:10

Ayman Hourieh