简体   繁体   中英

How to dynamically pass arguments as varargs in Java

I'm trying to write a program that will take an unknown number of arrays as input from the user and then print from them, the function that I wrote that print takes in varargs.

So what I'm trying to do is in my main method call print(arr1, arr2, arr3...) and dynamically change that so I don't have to set a restriction on how many arrays can be passed in.

My initial thought process was to store all the arrays in a 2d ArrayList and then unpack them, much like how JavaScript has the spread operator where you can have a 2d array and then do print(...inputArrays) , but it doesn't seem like Java allows this.

This method:

public void foo(String... args) {}

is effectively the same as:

public void foo(String[] args) {}

Really - check the bytecode, it's the same signature. Or try to make both of these methods in one class - the compiler won't let you, as they have the same signature. The one difference between String... and String[] is that any callers to String... get the syntax sugar of: Take all arguments passed in this position and create an array for them.

As a consequence, invoking a varargs method and passing in an array works fine:

public void foo(String... args) {
}

String[] a = new String[10];
foo(a); // compiles and runs fine.

The problem is that arrays in java are rather unwieldy, but varargs is based on them. You're on the right track to avoid them, but when trying to dynamically call varargsed methods you're forced into using them. To make matters worse, generics and arrays don't mix well either. Nevertheless:

getPermutations(inputArrayList.toArray(ArrayList[]::new));

should get you somewhere (this converts the arraylist into an array).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM