10

How do I pass a array without making it a seperate variable? For example I know this works:

class Test{
    public static void main(String[] args){
        String[] arbitraryStrings={"foo"};
        takesStringArray(arbitraryStrings);
    }
    public static void takesStringArray(String[] argument){
        System.out.println(argument);
    }
}

But I dont want to make the array a variable as it is only used here. Is there any way to do something like this:

class Test{
    public static void main(String[] args){
        takesStringArray({"foo"});
    }
    public static void takesStringArray(String[] argument){
        System.out.println(argument);
    }
}
Others
  • 2,876
  • 2
  • 30
  • 52
  • 2
    possible duplicate of [Passing directly an array initializer to a method parameter doesn't work](http://stackoverflow.com/questions/12805535/passing-directly-an-array-initializer-to-a-method-parameter-doesnt-work) – Rohit Jain Oct 23 '13 at 05:40
  • Consider taking a look at Groovy: http://groovy.codehaus.org/. In Groovy, you can just define list literals anywhere you like. it's sweet! – Ian Durkan Jan 07 '14 at 22:36

6 Answers6

26

{"foo"} doens't tell Java anything about what type of array you are trying to create...

Instead, try something like...

takesStringArray(new String[] {"foo"});
Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
2

You are able to create an array with new, and without A new variable

The correct syntax you are expecting is,

  takesStringArray(new String[]{"foo"});

Seems, you are just started with arrays.There are many other syntax's to declare an array.

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2
class Test {
    public static void main(String[] args) {
        takesStringArray(new String[]{"foo"});
    }

    public static void takesStringArray(String[] argument) {
        System.out.println(argument);
    }
}
Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
Jixi
  • 117
  • 1
  • 13
1

use in-line array declaration

try

takesStringArray(new String[]{"foo"});
upog
  • 4,965
  • 8
  • 42
  • 81
0

u may try VarArgs:

class Test{
    public static void main(String[] args){
        takesStringArray("foo", "bar");
    }
    public static void takesStringArray(String... argument){
        System.out.println(argument);
    }
}
0

You can use varargs:

class Test {
    public static void main(String[] args) {
        takesStringArray("foo");
    }

    public static void takesStringArray(String... argument) {
        System.out.println(argument);
    }  
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Korniltsev Anatoly
  • 3,676
  • 2
  • 26
  • 37