下面方法中字符串后面的3个点是什么意思?
public void myMethod(String... strings) {
// method body
}
下面方法中字符串后面的3个点是什么意思?
public void myMethod(String... strings) {
// method body
}
当前回答
A really common way to see a clear example of the use of the three dots it is present in one of the most famous methods in android AsyncTask ( that today is not used too much because of RXJAVA, not to mention the Google Architecture components), you can find thousands of examples searching for this term, and the best way to understand and never forget anymore the meaning of the three dots is that they express a ...doubt... just like in the common language. Namely it is not clear the number of parameters that have to be passed, could be 0, could be 1 could be more( an array)...
其他回答
这是Java传递变量(可变数量参数)的方法。
如果你熟悉C语言,这类似于…语法使用它的printf函数:
int printf(const char * format, ...);
但是以一种类型安全的方式:每个参数都必须符合指定的类型(在您的示例中,它们都应该是String)。
这是一个如何使用可变参数的简单示例:
class VarargSample {
public static void PrintMultipleStrings(String... strings) {
for( String s : strings ) {
System.out.println(s);
}
}
public static void main(String[] args) {
PrintMultipleStrings("Hello", "world");
}
}
…参数实际上是一个数组,所以你可以传递一个String[]作为参数。
这个特性叫做可变参数,是Java 5中引入的一个特性。这意味着函数可以接收多个String参数:
myMethod("foo", "bar");
myMethod("foo", "bar", "baz");
myMethod(new String[]{"foo", "var", "baz"}); // you can even pass an array
然后,你可以使用String变量作为数组:
public void myMethod(String... strings) {
for (String whatever : strings) {
// do what ever you want
}
// the code above is equivalent to
for (int i = 0; i < strings.length; i++) {
// classical for. In this case you use strings[i]
}
}
这个答案很大程度上借鉴了kiswa和Lorenzo的……也来自Graphain的评论。
A really common way to see a clear example of the use of the three dots it is present in one of the most famous methods in android AsyncTask ( that today is not used too much because of RXJAVA, not to mention the Google Architecture components), you can find thousands of examples searching for this term, and the best way to understand and never forget anymore the meaning of the three dots is that they express a ...doubt... just like in the common language. Namely it is not clear the number of parameters that have to be passed, could be 0, could be 1 could be more( an array)...
只要把它想象成c#中的关键字params,如果你来自那个背景的话:)
可以说,它是语法糖的一个例子,因为它无论如何都是作为一个数组实现的(这并不意味着它是无用的)——我更喜欢传递一个数组以保持它的清晰,并声明具有给定类型的数组的方法。不过,与其说是回答,不如说是意见。