Java 中参数类型旁边的 3 个点是什么意思? [英] What do 3 dots next to a parameter type mean in Java?

查看:28
本文介绍了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.

这篇关于Java 中参数类型旁边的 3 个点是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆