Java array initialization within argument list

前端 未结 4 1525
野趣味
野趣味 2020-12-11 15:21

How come the first call to someMethod doesn\'t compile without being explicit that it\'s String[]?

It\'s fine to use an array initializer to create a String[] arra

相关标签:
4条回答
  • 2020-12-11 15:54

    If you don't want to use explicit String[], use:

    public void someMethod(String... arr){
        //do some magic
    }
    …
    someMethod("cm", "applicant", "lead");
    

    The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

    Read more.

    0 讨论(0)
  • You can use the curly braces to initialize an array. In every else case it is used to define blocks of statments.

    0 讨论(0)
  • 2020-12-11 16:09

    You can only use the { "hello", "world" } initialization notation when declaring an array variable or in an array creation expression such as new String[] { ... }.

    See Section 10.6 Array Initializers in the Java Language Specification:

    An array initializer may be specified in a declaration, or as part of an array creation expression (§15.10), creating an array and providing some initial values

    0 讨论(0)
  • 2020-12-11 16:10

    Or you can use varargs:

    public void someMethod(String... arr){
        //do some magic
    }
    
    public void makeSomeMagic(){
        someMethod("cat", "fish", "cow");
    }
    

    It's basically a fancy syntax for an array parameter (vararg must be the last parameter in method signature).

    0 讨论(0)
提交回复
热议问题