Others
Others

Reputation: 3023

How to pass a function an array literal?

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);
    }
}

Upvotes: 10

Views: 9271

Answers (6)

Korniltsev Anatoly
Korniltsev Anatoly

Reputation: 3686

You can use varargs:

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

    public static void takesStringArray(String... argument) {
        System.out.println(argument);
    }  
}

Upvotes: 0

user2575725
user2575725

Reputation:

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);
    }
}

Upvotes: 0

Jixi
Jixi

Reputation: 117

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

    public static void takesStringArray(String[] argument) {
        System.out.println(argument);
    }
}

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347314

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

Instead, try something like...

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

Upvotes: 26

Suresh Atta
Suresh Atta

Reputation: 122006

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.

Upvotes: 2

upog
upog

Reputation: 5531

use in-line array declaration

try

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

Upvotes: 1

Related Questions