"..." being used in Java? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can I pass an array as arguments to a method with variable arguments in Java?
What is … in a method signature
I first saw this when I was modding Minecraft. It had a constructor that specified (String ... line), and thought it was just some shorthand that Mojang had created. But now, I was looking over ProcessBuider, and saw it again. I was wondering what this is used for. My best guess is that it allows developers to add as many of that type of object as they want. But if that's the case, why not just use an Array or List?
So, really, I am asking two questions:
What is the "..." operator, and
Why would it be more useful than using an Array or List?

... indicates a multiple argument list to a variadic function: a function that can take a variable number of arguments.
For an example of this, look at PrintStream.format. The first (required) argument is a format String, and the remaining 0 or more arguments fulfill that format.

It is called varargs, and as you say it is used to be able to let a method be called with any number of arguments of the specified type. It was introduced in Java 5.
You can read more in the Java tutorials - Varargs.

This is equivalent to a String[] line. It is Java's equivalent to the varargs keyword in C/C++. Similar to C/C++ it must appear as the last parameter.

You've already answered question #1 yourself. As to why it's more useful, it's just a shorthand that requires less typing.

To answer your second question, one advantage of varargs is that you can call a function taking varargs parameter without passing that param. Whereas instead if your function takes in an array, and you need to call it without any value, the caller needs to explicitly pass null.

Related

In Java, what does the notation `...` mean in the context of a prototype declaration: `type function_name (type... parameter_name)` [duplicate]

This question already has answers here:
What is the ellipsis (...) for in this method signature?
(5 answers)
Closed 7 years ago.
I'm learning Java, and in function prototypes I often see parameters of the variety type... parameter_name. What does the ... notation mean?
The New Features and Enhancements
J2SE 5.0 says (in part)
Varargs
This facility eliminates the need for manually boxing up argument lists into an array when invoking methods that accept variable-length argument lists. Refer to JSR 201.
It's also called a variadic function. Per the wikipedia,
In computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments.
Those are called varargs. When calling the method you can pass in any number of arguments for that parameter (even 0, so you can ignore it), or you can pass in an array. Inside the method the varags parameter is treated as an array.
For example, this method:
public void foo(String... strs) {}
Can be called with any of these:
foo();
foo("hello", "world");
String[] args = {"hello", "world"};
foo(args);
Inside the method you can access parameters like so:
String str1 = strs[0];
String str2 = strs[1];
One important thing to note is that a varargs parameter must be the last parameter in your method (It makes sense when you consider that the number of arguments passed can vary, so you have to resolve the other parameters first).

What's the meaning of three dots in parameter declaration? [duplicate]

This question already has answers here:
What do 3 dots next to a parameter type mean in Java?
(9 answers)
Closed 9 years ago.
What do the three dots after "Object" mean in this parameter declaration:
public static int queryCount (
Connection conn, String whereClause,
Object ... params)
throws Exception
In what way does it differ from the parameter declaration Object params ?
Three dots mean that there method can get as parameters as much argument of type Object as it likes. Reading more about "varargs" arguments could be helpful.
This feature was introduced in Java to hide the process of using Arrays as parameters, in form of varargs.
As the documentation states, the process is stil same but complexity has been reduced.
Please note following points:
This allows for entering an array or sequence of type specified.
This form must be used at last in parameters list.
This is not available in older version, so be careful if you plan to deploy to older versions of Java
In short, it's a syntactic sugar for array with restriction that this should be the last parameter in arguments list.
e.g. it's totally legal to declare main method as follows
public static void main(String... args) {}
And another feature of this, this argument is optional, but you still will get an empty array as a value of argument.

Difference between byte[] and byte ... in Java Methods

Someone asked me what the difference between the two method parameters and why you would use the ... over specifically assigned array.
putMessage(byte ...send)
putMessage(byte[] send)
I couldn't answer them with confidence and couldn't remember what the ... is called.
The ... in your first example are called varargs. Your second example has an array argument. Varargs are a convenience for times when you want to hard code a variable number of arguments to a method but don't want to manually create an array to hold them. It's a shorthand notation. Consider this:
putMessage(0b00100101, 0b00100101, 0b00100101); // varargs
vs. this:
putMessage(new byte[] { 0b00100101, 0b00100101, 0b00100101 }); // array
The first example is less cluttered and more readable.
The parameters with ellipses are generally referred to as "varargs" if you want to google that.
Using varargs allows you to call a method with variable number of arguments without having to specify an array e.g.
public void printStr(String ...strings) {
for (String s : strings) {
System.out.println(s);
}
}
> printStr("Hello", "World")
Hello
World
So varargs allow a certain degree of convenience, but there are downsides - the varargs parameter must be the last parameter in the method signature, and thus you cannot have more than one varargs parameter to a method. If you want to pass multiple arrays to a method you have to use arrays, not varargs.
Another reason you might see arrays in some places where you might expect varargs is that varargs were only introduced in Java 5 - older code and code that needs to be backwards compatible will still be using arrays even where it might make more sense conceptually to use varargs.
The advantage of using varargs in the method signature is flexibility - there are some situations where the caller will have an array ready anyway and some where they will just have several arguments. Varargs will accept either the array or each variable as a separate argument, saving the caller the trouble of instantiating and populating an array.
The first one is with Varargs.
In short
A. First can be used to call with single byte type arg, 2 byte args.. or many args or an array.
B. second will be used with array only.
The ellipsis (three dots) indicates that you are using "varargs".
See http://download.oracle.com/javase/1,5.0/docs/guide/language/varargs.html for more details.
Inside the method, you access the elements of "send" as an array. The two methods are the same in that regard. The convenience is for the caller. In the second putMessage, the caller is compelled to create an array of bytes to pass to putMessage. In the first putMessage, the caller can simply say "putMessage(byte1, byte2)" or "putMessage(byte1, byte2, byte3)" or "putMessage(byte1)" -- variable number of arguments, or varargs.
The ellipses (...) allow you to inline N parameters of a type to a function call without having to define an array first. In the end you do simply get an array of parameters but it's basically shorthand or syntactic sugar. Also your client code might be a little cleaner and more declarative with the ellipses syntax... though it could easily go the other way and become mucky and unreadable.
Here's a great example of the ellipses syntax (variable length argument lists.) While looking at the sample consider what the client code (in the main function) would look like if an array was used instead of a variable length argument list.

What does a ... do as a parameter of a java function? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Java array argument “declaration” syntax
What is the ellipsis for in this method signature?
I've stumbled upon a function that has a String... strings as a parameter. What is the significance of this? I'm assuming it means any number of string arguments but isn't that the point of List?
function doStuff(String... strings) {
//Code
}
I'd appreciate an explanation of its purpose and usage in applications. Thanks
I is the syntax for specifying varargs i.e. specifying that a method can take a variable number of arguments.
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. Varargs can be used only in the final argument position.
It's the Ellipsis. It allows varargs, see:
What is the ellipsis (...) for in this method signature?

JSR223: Calling Java "varargs" methods from script

I have a method that looks like this on Java:
public void myMethod(Object... parms);
But I can't call this method as expected from the scripts.
If, in ruby, I do:
$myObject.myMethod(42);
It gives me org.jruby.exceptions.RaiseException: could not coerce Fixnum to class [Ljava.lang.Object
If I try the following in Javascript:
myObject.myMethod(42);
Then it gives me sun.org.mozilla.javascript.internal.EvaluatorException: Can't find method MyClass.test(number). (#2) in at line number 2
Of course, if I change the signature to take one single object then it works.
I assume that this is because someone along the line does not know how to convert, say Integer to Integer[] with the value at the first position.
I believe something like myMethod({42, 2009}) would work in Ruby, but this seems ugly - I wanted to be able to just do myMethod(42, 2009) to make it less confusing, specially for other languages. Is there any better workaround for this?
Thanks.
Java internally treats the variable-length argument list as an array whose elements are all of the same type. That is the reason why you need to provide an array of objects in your JRuby script.
It works like this:
myMethod [42, 2009].to_java
The to_java method constructs a Java array from a Ruby array. By default, to_java constructs Object arrays as needed in this case. If you need a String array you would use
["a","b","c"].to_java(:string)
More on this at the JRuby wiki
It seems like this is a known bug in jruby. See method dispatch on Java objects / classes should try to find a matching varargs method and NameError thrown when trying to pass argument to a Java method that is defined as having variable length arguments.
According to the link Rhino does support vararg.
Varargs are handled by the compiler as an Object[] which is what the error message describes.
I do not have JRuby experience, but does it work if you have an array argument?

Categories

Resources