Hert
Hert

Reputation: 23

Use an array without declaring it in a variable

If you try to do 15/2 it will return 7 because it thinks that 15 and 2 are integers. If you do (double)15/2 it will return 7.5 because it knows that 15 is a double.

Say you have a function named test() that takes in an array as an argument. How would you pass an array into the function without defining it first?

I have tried doing something like this:

test((int[]){1,2,3,4})

Upvotes: 2

Views: 55

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201517

I think you are looking for a variadic function (aka varargs), something like

public static double test(int... vals) {
    return IntStream.of(vals).sum() / (double) vals.length;
}

can be called with any number of int(s). For example,

System.out.println(test(1, 2, 3));

Which outputs

2.0

Upvotes: 2

Robby Cornelissen
Robby Cornelissen

Reputation: 97331

You're pretty close. You can do it like this:

test(new int[]{1, 2, 3, 4});

Upvotes: 4

Related Questions