I have the following code
String[] args = {"a", "b", "c"};
method(args);
private void method(String[] args){
return args;
}
Why can I not do the following without errors?
method({"a", "b", "c"});
This code is example just to prove the point, not the actual methods I am using. I would like to do the second method instead to clean up my code, and avoid declaring a dozen different arrays when I only use them once to pass to my method.
The heart of the question is what is the most efficient way to pass an array of strings as a method paramter.
I suspect you want to use varargs. You don't even need to create an array to sent variable length arguments.
String[] strings = method("a", "b", "c");
private String[] method(String... args){
return args;
}
or
String[] strings = array("a", "b", "c");
private <T> T[] array(T... args){
return args;
}
or if you want to condense futher
String[] strings = array("a, b, c");
private String[] array(String args){
return args.split(", ?");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With