简体   繁体   中英

Passing array as argument BUT individually

I want to have an abstract function such as

init(int... conditions);

So that inherited classes can have variety of init conditions; may some classes require less number of arugments and may others will take more than the others.

However I wish to rather pass them individually like following

init(arr[0], arr[1], arr[2]... arr[size-1]);

than

init(arr);

Is such approach possible? If not, then should I be better of just passing an array?


Sorry for the confusion that I seem to create.

I have an array of size n that varies. I cannot hard code passing the argument because the number of arguments is dependable. I do not want to go for function overload for different versions of init method because that will create about dozen of different versions of init method.

You don't need to overload the method. Just use the so called variable arguments . The are available in Java since version 1.5. For example:

public void init(int... conditions) { ... }

You can use the method in two ways:

  1. Pass the array itself. Like this:

    init(array);

  2. Pass each of the array elements. Like this:

    init(array[0], array[1], ... array[n]);

Note that if you want to have other arguments for this method, they should be placed in the method signature only before the variable arguments.

You can always use the variable arguments method parameter. In fact it has the same method signature as what you posted above.

public void init(int... conditions){}

This makes conditions an int[], which you can iterate over to get your init conditions.

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