可变长度参数在 Java 中是否被视为数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23168342/
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
Is a variable length argument treated as an array in Java?
提问by
As I understand an array
consists of fixed number of elements and a variable length argument
takes as many number of arguments as you pass (of the same type). But are they same? Can I pass one where the other is expected?
据我了解, aarray
由固定数量的元素组成, avariable length argument
接受尽可能多的参数(相同类型)。但它们是一样的吗?我可以在另一个预期的地方通过一个吗?
采纳答案by Jon Skeet
Yes, if you have a method with a varargs parameter like this:
是的,如果您有一个带有 varargs 参数的方法,如下所示:
public void foo(String... names)
and you call it like this:
你这样称呼它:
foo("x", "y", "z");
then the compiler just converts that into:
然后编译器只是将其转换为:
foo(new String[] { "x", "y", "z"});
The type of the names
parameter is String[]
, and can be used just like any other array variable. Note that it couldstill be null
:
names
参数的类型是String[]
,并且可以像任何其他数组变量一样使用。请注意,它可能仍然是null
:
String[] nullNames = null;
foo(nullNames);
See the documentation for varargsfor more information.
This does notmean that varargs are interchangeable with arrays - you still need to declare the method to accept varargs. For example, if your method were declared as:
但这并不意味着可变参数与阵列互换-你仍然需要声明接受可变参数的方法。例如,如果您的方法被声明为:
public void foo(String[] names)
then the first way of calling it would not compile.
那么第一种调用它的方法将无法编译。
回答by Sam G-H
A simple test would suggest that they are the same:
一个简单的测试表明它们是相同的:
public class test {
public static void varArgs(String... strings) {
for (String s : strings) {
System.out.println(s);
}
}
public static void main(String[] args) {
String[] strings = {"string1", "string2", "string3"};
varArgs(strings);
varArgs("string4", "string5", "string6");
}
}
Outputs:
输出:
string1
string2
string3
string4
string5
string6
回答by Petr Mensik
They are the same, array is internally used by JVM when creating varargs methods. So you can treat vararg argument in the same way you treat array so use for instance enhanced for loop
它们是相同的,数组在创建可变参数方法时由 JVM 内部使用。所以你可以像对待数组一样对待 vararg 参数,所以使用例如增强的 for 循环
public void method(String... args) {
for(String name : args) {
//do something
}
}
and call it like this or even pass an array
并像这样调用它甚至传递一个数组
method("a", "b", "c");
method(new String[] {"a", "b", "c"});
See this nice articlefor further explanation.
请参阅这篇不错的文章以获得进一步的解释。