34

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.

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
covertbob
  • 691
  • 2
  • 8
  • 15

2 Answers2

36

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)

Community
  • 1
  • 1
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
  • 1
    Hi dreamcrash! I was just thinking that an example would be cool to add to your post, as well as what Java version this applies to. I'm stuck on Java 6 due to being on Google's App Engine, but I know the newer Java versions have some pretty cool new features. Hope this helps! :) – jamesmortensen Dec 02 '12 at 02:50
  • 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. i.e. `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)` - is **legal**. – LivePwndz Mar 24 '16 at 07:41
  • Yep you are right I Will add this information to my post as soon as possible, thanks. – dreamcrash Mar 24 '16 at 20:03
3

It's called VarArgs http://www.javadb.com/using-varargs-in-java. In this case, it means you can put multiple instances of Object as a parameter to doAction() as many as you wants :

doAction(new Object(), new Object(), new Object());
Yohanes Gultom
  • 3,782
  • 2
  • 25
  • 38