java 在方法定义期间用作参数的一部分时,三个点 (...) 表示什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11690917/
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
What do three dots (...) indicate when used as a part of parameters during method definition?
提问by Vikram
What do three dots (...) indicate when used as a part of parameters during method definition?
在方法定义期间用作参数的一部分时,三个点 (...) 表示什么?
Also, is there any programming term for the symbol of those 3 dots?
另外,这三个点的符号有什么编程术语吗?
I noticed in a code sample:
我在代码示例中注意到:
public void method1 (Animal... animal) {
// Code
}
And this method was called from 2 places. The arguments passed while calling were different in both scenarios though:
这个方法是从 2 个地方调用的。调用时传递的参数在两种情况下都不同:
Array of objects is passed as an argument to method1(Animal...)
Object of class Animal passed as an argument to method1(Animal...)
对象数组作为参数传递给 method1(Animal...)
类 Animal 的对象作为参数传递给 method1(Animal...)
So, is it something like, if you are not sure whether you will be passing a single element of an array or the entire array as an argument to the method, you use 3 dots as a part of parameters in the method definition?
那么,是否是这样,如果您不确定是将数组的单个元素还是整个数组作为参数传递给方法,则在方法定义中使用 3 个点作为参数的一部分?
Also, please let me know if there is any programming term for the symbol of those 3 dots.
另外,请让我知道这三个点的符号是否有任何编程术语。
采纳答案by corsiKa
It's called varargs.
它被称为可变参数。
It means you can pass as many of that type as you want.
这意味着您可以根据需要传递任意数量的该类型。
It actually translates it into method1(Animal[] a)
and you reference them as a[1]
like you would any other array.
它实际上将其转换method1(Animal[] a)
为a[1]
您可以像引用任何其他数组一样引用它们。
If I have the following
如果我有以下
Cat whiskers = new Cat();
Dog rufus = new Dog();
Dolphin flipper = new Dolphin();
method1(whiskers, rufus, flipper); // okay!
method1(rufus); // okay!
method1(); // okay!
method1(flipper,new Parakeet()); // okay!
回答by pcalcao
That means that the method accepts an Array of that type of Objects but, that array is created automatically when you pass several Objects of that type separated by commas.
这意味着该方法接受该类型对象的数组,但是,当您传递多个以逗号分隔的该类型对象时,该数组会自动创建。
Keep in mind that there can only be one vararg parameter of a given type in a method signature, and you can't have another argument of the same type in the signature following the vararg (obviously, there would be no way of distinguishing between the two).
请记住,方法签名中只能有一个给定类型的 vararg 参数,并且在 vararg 之后的签名中不能有另一个相同类型的参数(显然,无法区分二)。
回答by omar
It means that zero or more String objects (or an array of them) may be passed as the parameter(s) for that function.
这意味着可以将零个或多个 String 对象(或它们的数组)作为该函数的参数传递。
Maybe:
或许:
x("foo", "bar");
x("foo", "bar", "baz");