Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, most efficient way to pass String array as Method Parameter [duplicate]

Tags:

java

arrays

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.

like image 650
Dan Ciborowski - MSFT Avatar asked Jul 30 '13 07:07

Dan Ciborowski - MSFT


1 Answers

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(", ?");
}
like image 168
Peter Lawrey Avatar answered Sep 22 '22 05:09

Peter Lawrey