Antescript: I’m aware that there’s a prior SO question whose title sounds like it refers to the exact same question. It doesn’t.
Anyway, this question is a little weird – there are plenty of better ways to work around the issues here, but I’m curious as to how I could solve my particular dilemma.
Let’s say I have a method that uses varargs to accept an arbitrary number of elements, perhaps of type Integer. If I have an arbitrary-length array of Integers, is there a way for me to call my method with a comma-separated param list composed of each element of said array?
Here’s a brief, contrived example:
Integer[] paramList = new Integer {1, 2, 3};
varMethod(paramList[0], paramList[1], paramList[2]);
// varMethod({{for (param : paramList) {param;}}});
public void varMethod(Integer...values) {
for (Integer value : values) {
foo(value);
}
}
That commented-out line hints at what I want to do. Since the paramList integer is arbitrary length, calling varMethod with each element explicitly requested (line 2) won’t work. What I’m wondering is if there’s a way to dynamically generate the comma-separated param list from the elements of an array.
Again, I realize that in an example like this, there are better ways to approach the entire problem, but please be aware that I’ve simplified the code so that it’s only relevant to the particular issue we’re discussing here. Any workarounds that address my posted code won’t generalize to the problem I’m really working on that led me to formulate this question in the first place.
I think you’re just looking for:
Perhaps you didn’t realize that
Integer...is a special variant of a normalInteger[]array. Thus sinceparamListis already anInteger[]array, you can just pass it directly into the method.