Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function an array literal?

Tags:

java

arrays

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);
    }
}
like image 808
Others Avatar asked Oct 23 '13 05:10

Others


People also ask

Can you pass an array to a function?

Answer: An array can be passed to a function by value by declaring in the called function the array name with square brackets ( [ and ] ) attached to the end. When calling the function, simply pass the address of the array (that is, the array's name) to the called function.

What is an array literal?

Array literals An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ( [] ). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.

Can you pass by reference an array?

Arrays can be passed by reference OR by degrading to a pointer. For example, using char arr[1]; foo(char arr[]). , arr degrades to a pointer; while using char arr[1]; foo(char (&arr)[1]) , arr is passed as a reference. It's notable that the former form is often regarded as ill-formed since the dimension is lost.

What is advantage of passing array as function argument?

Advantages of Passing Arrays to FunctionsPassing similar elements as an array takes less time than passing each element to a function as we are only passing the base address of the array to the function, and other elements can be accessed easily as an array is a contiguous memory block of the same data types.


1 Answers

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

Instead, try something like...

takesStringArray(new String[] {"foo"});
like image 79
MadProgrammer Avatar answered Sep 27 '22 19:09

MadProgrammer