Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

java - Java,参数中有3个点(Java, 3 dots in parameters)

What do the 3 dots in the following method mean?

(以下方法中的三个点是什么意思?)

public void myMethod(String... strings){
    // method body
}
  ask by Vikram translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

(请参见此处的“任意数量的参数”部分: 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.

(确保在方法主体中以这种方式对待它。)

Important Note 2: The argument that gets the ... must be the last in the method signature.

(重要说明2:获取...的参数必须是方法签名中的最后一个。)

So, myMethod(int i, String... strings) is okay, but myMethod(String... strings, int i) is not okay.

(因此, myMethod(int i, String... strings)可以,但是myMethod(String... strings, int i)则可以。)

Thanks to Vash for the clarifications in his comment.

(感谢Vash在他的评论中的澄清。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...