Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Varargs in a group?

About Varargs, can i repeat the arguments in a group?

For instance, i want to allow users pass in:

myFunc(1, "one");
myFunc(1, "one", 2, "two");
myFunc(1, "one", 2, "two", 3, "three");

It seems impossible. But as mentioned in the docs, the varargs is in fact an array, in old implementation. i would like to know how was people do before varargs is invented. That might inspire us how to achieve the above scenario. We can regard my scenario as {int, String}... repeating afterall.

Thanks for any input :-)

Edit:

Thanks for all your inputs!

So, is it calling by myFunc(new wrap(1, "one"), new wrap(2, "two"), new wrap(3, "three")); is the old method?

Edit 2:

Well, nope. Thats my fault of confusion.

For

myFunc(1);
myFunc(1, 2);
myFunc(1, 2, 3);

the old way should be

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

As far as i can see, as the repeating arguments form an array. All its arguments has to be of the same type. It should be impossible to achieve the above calls in a simple way. For curiosity, i start thinking of the possibility of operator overloading ... (?)

like image 433
midnite Avatar asked Jan 13 '23 16:01

midnite


1 Answers

In this case, it seems to me that it's suitable to create a datastructure for your "pair", and then use that type as vararg argument to your method.

public void myFunc(Pair... pairs) {}

You could also use Object..., but I don't see any advantages in this case, since the arguments always come in pairs.

like image 135
NilsH Avatar answered Jan 21 '23 11:01

NilsH