Java 方法的参数中的“int...”是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34978244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:36:47  来源:igfitidea点击:

What is "int..." in Java method's parameter?

java

提问by user1860288

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?

“int...”似乎表示整数参数的数量不确定,但该变量在函数内部用作数组。有人可以解释一下吗?

回答by Marcinek

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

正如您已经正确说明的那样,此 java 符号是使该方法接受可变数量的(在本例中)int 参数。

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

要处理这种可变数量的变量,您可以像访问数组一样访问它。

This functionality is introduced in java 5.

这个功能是在 java 5 中引入的。

See also here:

另见此处:

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

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

回答by Theodoros Chatzigiannakis

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_argand va_endmacros. Different languages may have something else.

当您有可变数量的潜在参数时,您需要某种方法来迭代它们 - 否则它们在实践中不是很有用。Java 和 C# 恰好具有数组索引语法。C 和 C++ 碰巧有va_start,va_argva_end宏。不同的语言可能有别的东西。

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.

Java 之所以特别使用数组语法,可能是因为它恰好与它们的实际实现方式相匹配:作为在编译时替换的简单数组参数