What do 3 dots next to a parameter type mean in Java?

前端 未结 12 1712
灰色年华
灰色年华 2020-11-22 00:27

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

public void myMethod(String... strings){
    // method body
}
12条回答
  •  逝去的感伤
    2020-11-22 00:38

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

    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.

    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.

    Thanks to Vash for the clarifications in his comment.

提交回复
热议问题