在Java中,参数类型旁边的3点是什么意思?

在Java中,参数类型旁边的3点是什么意思?

问题描述:

以下方法中String后面的三个点是什么意思?

What do the 3 dots following String in the following method mean?

public void myMethod(String... strings){
    // method body
}

这意味着可以将零个或多个String对象(或它们的单个数组)作为该方法的参数传递.

It means that zero or more String objects (or a single array of them) may be passed as the argument(s) for that method.

参见任意数量的参数".此处的部分: http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html#varargs

See the "Arbitrary Number of Arguments" section here: http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html#varargs

在您的示例中,您可以将其称为以下任意一项:

In your example, you could call it as any of the following:

myMethod(); // Likely useless, but possible
myMethod("one", "two", "three");
myMethod("solo");
myMethod(new String[]{"a", "b", "c"});

重要说明:以这种方式传递的参数始终是一个数组-即使只有一个.确保在方法主体中以这种方式对待它.

Important Note: The argument(s) passed in this way is always an array - even if there's just one. Make sure you treat it that way in the method body.

重要说明2:获取...的参数必须是方法签名中的最后一个.因此,myMethod(int i, String... strings)可以,但是myMethod(String... strings, int i)不能.

Important Note 2: The argument that gets the ... must be the last in the method signature. So, myMethod(int i, String... strings) is okay, but myMethod(String... strings, int i) is not okay.

感谢瓦什(Vash)在其评论中的澄清.

Thanks to Vash for the clarifications in his comment.