What is the ellipsis (…) for in this method signature?

前端 未结 5 2147
青春惊慌失措
青春惊慌失措 2020-11-22 06:23

In the App Engine docs, what is the ellipsis (JID...) for in this method signature?

public MessageBuilder withRecipientJids(JID... recipientJids         


        
5条回答
  •  醉话见心
    2020-11-22 06:59

    The way to use the ellipsis or varargs inside the method is as if it were an array:

    public void PrintWithEllipsis(String...setOfStrings) {
        for (String s : setOfStrings)
            System.out.println(s);
    }
    

    This method can be called as following:

    obj.PrintWithEllipsis(); // prints nothing
    obj.PrintWithEllipsis("first"); // prints "first"
    obj.PrintWithEllipsis("first", "second"); // prints "first\nsecond"
    

    Inside PrintWithEllipsis, the type of setOfStrings is an array of String. So you could save the compiler some work and pass an array:

    String[] argsVar = {"first", "second"};
    obj.PrintWithEllipsis(argsVar);
    

    For varargs methods, a sequence parameter is treated as being an array of the same type. So if two signatures differ only in that one declares a sequence and the other an array, as in this example:

    void process(String[] s){}
    void process(String...s){}
    

    then a compile-time error occurs.

    Source: The Java Programming Language specification, where the technical term is variable arity parameter rather than the common term varargs.

提交回复
热议问题