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

前端 未结 12 1710
灰色年华
灰色年华 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:33

    That feature is called varargs, and it's a feature introduced in Java 5. It means that function can receive multiple String arguments:

    myMethod("foo", "bar");
    myMethod("foo", "bar", "baz");
    myMethod(new String[]{"foo", "var", "baz"}); // you can even pass an array
    

    Then, you can use the String var as an array:

    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]
        }
    }
    

    This answer borrows heavily from kiswa's and Lorenzo's... and also from Graphain's comment.

提交回复
热议问题