Java,参数中有3个点 [英] Java, 3 dots in parameters

查看:89
本文介绍了Java,参数中有3个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下方法中的3个点是什么意思?

What do the 3 dots in the following method mean?

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


推荐答案

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

It means that zero or more String objects (or an 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天全站免登陆