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

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

    This is the Java way to pass varargs (variable number arguments).

    If you are familiar with C, this is similar to the ... syntax used it the printf function:

    int printf(const char * format, ...);
    

    but in a type safe fashion: every argument has to comply with the specified type (in your sample, they should be all String).

    This is a simple sample of how you can use varargs:

    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");
       }
    }
    

    The ... argument is actually an array, so you could pass a String[] as the parameter.

提交回复
热议问题