Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of ellipsis(...) in Java? [duplicate]

I was looking through some code and saw the following notation. I'm somewhat unsure what the three dots mean and what you call them.

void doAction(Object...o); 

Thanks.

like image 670
covertbob Avatar asked Dec 02 '12 02:12

covertbob


People also ask

What are ellipsis used for in Java?

The three dot (...) notation is actually borrowed from mathematics, and it means "...and so on". As for its use in Java, it stands for varargs , meaning that any number of arguments can be added to the method call.

How do you use three dots in Java?

Syntax: (Triple dot ... ) --> Means we can add zero or more objects pass in an arguments or pass an array of type object. Definition: 1) The Object ... argument is just a reference to an array of Objects.

What is the type of varargs in Java?

Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body }


1 Answers

It means that this method can receive more than one Object as a parameter. To better understating check the following example from here:

The ellipsis (...) identifies a variable number of arguments, and is demonstrated in the following summation method.

static int sum (int ... numbers) {    int total = 0;    for (int i = 0; i < numbers.length; i++)         total += numbers [i];    return total; } 

Call the summation method with as many comma-delimited integer arguments as you desire -- within the JVM's limits. Some examples: sum (10, 20) and sum (18, 20, 305, 4).

This is very useful since it permits your method to became more abstract. Check also this nice example from SO, were the user takes advantage of the ... notation to make a method to concatenate string arrays in Java.

Another example from Variable argument method in Java 5

public static void test(int some, String... args) {         System.out.print("\n" + some);         for(String arg: args) {             System.out.print(", " + arg);         }     } 

As mention in the comment section:

Also note that if the function passes other parameters of different types than varargs parameter, the vararg parameter should be the last parameter in the function declaration public void test (Typev ... v , Type1 a, Type2 b) or public void test(Type1 a, Typev ... v recipientJids, Type2 b) - is illegal. ONLY public void test(Type1 a, Type2 b, Typev ... v)

like image 134
dreamcrash Avatar answered Oct 02 '22 13:10

dreamcrash