简体   繁体   English

如何在 Java 中将 arguments 作为可变参数动态传递

[英]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.我正在尝试编写一个程序,它将未知数量的 arrays 作为用户的输入,然后从他们那里打印,我写的 function 使用可变参数。

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.所以我要做的是在我的主要方法调用print(arr1, arr2, arr3...)并动态更改它,因此我不必限制可以传入多少 arrays。

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.我最初的想法是将所有 arrays 存储在 2d ArrayList 中,然后解压它们,就像 JavaScript 有扩展运算符,然后你可以输入数组并print(...inputArrays)似乎 Java 允许这样做。

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.或者尝试在一个 class 中使用这两种方法 - 编译器不会让你这样做,因为它们具有相同的签名。 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. String...String[]之间的一个区别是,任何对String...调用者都会获得以下语法糖:获取在此 position 中传递的所有 arguments 并为它们创建一个数组。

As a consequence, invoking a varargs method and passing in an array works fine:因此,调用 varargs 方法并传入数组可以正常工作:

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.问题是 java 中的 arrays 相当笨拙,但可变参数是基于它们的。 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.更糟糕的是,generics 和 arrays 也不能很好地混合。 Nevertheless:尽管如此:

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

should get you somewhere (this converts the arraylist into an array).应该可以带您到某个地方(这会将 arraylist 转换为数组)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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