Java array initialization within argument list
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[] array but you can't use it to pass an argument. Are the curly braces used in some other fashion for passing arguments that derails how I'd expect this to behave?
开发者_如何学JAVApublic void someMethod(String[] arr){
//do some magic
}
public void makeSomeMagic(){
String[] arr = {"cat", "fish", "cow"};
//Does not compile!
someMethod({"cat", "fish", "cow"});
//This compiles!
someMethod(new String[]{"cat", "fish", "cow"});
//This compiles!
someMethod(arr);
}
The compiler error is the following:
The method someMethod(String[]) in the type Moo is not applicable for the arguments (String, String, String)
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
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.
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).
You can use the curly braces to initialize an array. In every else case it is used to define blocks of statments.
精彩评论