3

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:

  1. What is the "..." operator, and
  2. Why would it be more useful than using an Array or List?
Community
  • 1
  • 1
mattbdean
  • 2,532
  • 5
  • 26
  • 58

5 Answers5

2

... 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.

pb2q
  • 58,613
  • 19
  • 146
  • 147
2

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.

Keppil
  • 45,603
  • 8
  • 97
  • 119
1

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.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

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

Dmitry B.
  • 9,107
  • 3
  • 43
  • 64
  • I wouldn't say it's short hand. I would say it's convince as it allows you to pass 0/1 or more parameters without the need to supply multiple method signatures – MadProgrammer Aug 13 '12 at 22:59
0

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.