简体   繁体   English

变量长度参数是否被视为Java中的数组?

[英]Is a variable length argument treated as an array in Java?

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). 据我所知, array由固定数量的元素组成,并且variable length argument在传递时使用相同数量的参数(相同类型)。 But are they same? 但他们一样吗? Can I pass one where the other is expected? 我可以通过一个预期的另一个吗?

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. names参数的类型是String[] ,可以像任何其他数组变量一样使用。 Note that it could still be null : 请注意,它可能仍然是null

String[] nullNames = null;
foo(nullNames);

See the documentation for varargs for more information. 有关更多信息,请参阅varargs文档

This does not mean 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. 那么调用它的第一种方法就不会编译。

They are the same, array is internally used by JVM when creating varargs methods. 它们是相同的,JVM在创建varargs方法时内部使用该数组。 So you can treat vararg argument in the same way you treat array so use for instance enhanced for loop 所以你可以像处理数组一样对待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 article for further explanation. 有关详细说明,请参阅此文章

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM