在方法定义期间用作参数的一部分时,三个点 (...) 表示什么? [英] What do three dots (...) indicate when used as a part of parameters during method definition?
问题描述
在方法定义期间用作参数的一部分时,三个点 (...) 表示什么?
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
}
这个方法是从 2 个地方调用的.调用时传递的参数在两种情况下都不同:
And this method was called from 2 places. The arguments passed while calling were different in both scenarios though:
对象数组作为参数传递给 method1(Animal...)
Array of objects is passed as an argument to method1(Animal...)
Animal 类的对象作为参数传递给 method1(Animal...)
Object of class Animal passed as an argument to method1(Animal...)
那么,是否是这样,如果您不确定是将数组的单个元素还是整个数组作为参数传递给方法,则在方法定义中使用 3 个点作为参数的一部分?
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?
另外,请告诉我这三个点的符号是否有任何编程术语.
Also, please let me know if there is any programming term for the symbol of those 3 dots.
推荐答案
它叫做 varargs.
It's called varargs.
这意味着您可以根据需要传递任意数量的该类型.
It means you can pass as many of that type as you want.
它实际上将其转换为 method1(Animal[] a)
并且您将它们引用为 a[1]
就像您引用任何其他数组一样.
It actually translates it into method1(Animal[] a)
and you reference them as a[1]
like you would any other array.
如果我有以下内容
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!
这篇关于在方法定义期间用作参数的一部分时,三个点 (...) 表示什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!