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

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

    Syntax: (Triple dot ... ) --> Means we can add zero or more objects pass in an arguments or pass an array of type object.

    public static void main(String[] args){}
    public static void main(String... args){}
    

    Definition: 1) The Object ... argument is just a reference to an array of Objects.

    2) ('String []' or String ... ) It can able to handle any number of string objects. Internally it uses an array of reference type object.

    i.e. Suppose we pass an Object array to the ... argument - will the resultant argument value be a two-dimensional array - because an Object[] is itself an Object:
    

    3) If you want to call the method with a single argument and it happens to be an array, you have to explicitly wrap it in

    another. method(new Object[]{array}); 
    OR 
    method((Object)array), which will auto-wrap.
    

    Application: It majorly used when the number of arguments is dynamic(number of arguments know at runtime) and in overriding. General rule - In the method we can pass any types and any number of arguments. We can not add object(...) arguments before any specific arguments. i.e.

    void m1(String ..., String s) this is a wrong approach give syntax error.
    void m1(String s, String ...); This is a right approach. Must always give last order prefernces.   
    

提交回复
热议问题