2

I came across a method definition:

void doType(int... keyCodes) {
  doType(keyCodes, 0, keyCodes.length);
}

void doType(int[] keyCodes, int offset, int length) {
  if (length == 0) {
    return;
  }

  robot.keyPress(keyCodes[offset]);
  doType(keyCodes, offset + 1, length - 1);
  robot.keyRelease(keyCodes[offset]);
}

The "int..." seems to indicate an indeterminate number of integer parameters but the variable is used as an array inside the function. Can someone please explain?

user1860288
  • 512
  • 2
  • 6
  • 18

2 Answers2

6

As you already stated correctly this java notation is to make the method accept a variable amount of (in this case) int parameter.

To handle this variable amount of variables you can access it like an array.

This functionality is introduced in java 5.

See also here:

https://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

Marcinek
  • 2,144
  • 1
  • 19
  • 25
2

You are right in deducing that the ellipses indicate that this method is variadic.

When you have a variable number of potential arguments, you need some way to iterate over them - otherwise they aren't very useful in practice. Java and C# happen to have the array indexing syntax. C and C++ happen to have the va_start, va_arg and va_end macros. Different languages may have something else.

The reason why Java has the array syntax specifically is probably because it happens to match the way they are actually implemented: as a simple array parameter replaced at compile time.

Community
  • 1
  • 1
Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104