11

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.

Dan Ciborowski - MSFT
  • 6,807
  • 10
  • 53
  • 88
  • 1
    possible duplicate of [Why passing {a, b, c} to a method doesn't work?](http://stackoverflow.com/questions/1017486/why-passing-a-b-c-to-a-method-doesnt-work) see also [Java: array initialization syntax](http://stackoverflow.com/questions/5387643/java-array-initialization-syntax) and especially [Why array constants can only be used in initializers?](http://stackoverflow.com/q/10520617/139010) – Matt Ball Jul 30 '13 at 07:31
  • Edited question, and redefined goal of answer to be more specifcly about most efficient way to pass array as parameters, provided links do not discuss varargs, therefor question should no longer be considered duplicate. – Dan Ciborowski - MSFT Jul 30 '13 at 08:01
  • Incidentally, your edited question _still_ doesn't mention varargs. – Matt Ball Jul 30 '13 at 14:40
  • Solution does... I had never heard of them until answer. – Dan Ciborowski - MSFT Jul 30 '13 at 14:48
  • I think you should ask a new question. You're asking *exactly* the same as the duplicate, and the added last sentence IMO doesn't change that at all. – Uli Köhler Mar 02 '14 at 23:22

4 Answers4

18

try

method(new String[]{ "a", "b", "c"});

that way the system knows it is a new string-array.

java is not like php ;)

bas
  • 1,678
  • 12
  • 23
7

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(", ?");
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
6

If you use:

method({ "a", "b", "c"});

then java has no idea whether you want an array of String or of Object. You can explicitly tell java what kind of array it is like this:

method(new String[] { "a", "b", "c"});

That way Java can tell that you mean an array of String.

tbodt
  • 16,609
  • 6
  • 58
  • 83
2

You do not need a named reference to the array. You can initialize and pass an anonymous array like this:

method (new String[]{"a", "b"});
Philipp
  • 67,764
  • 9
  • 118
  • 153