简体   繁体   English

将数组作为参数单独传递

[英]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; 这样继承的类可以有各种init条件; 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. 我有一个大小为n的数组变化。 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. 我不想为不同版本的init方法寻找函数重载,因为这将创建大约十几个不同版本的init方法。

You don't need to overload the method. 您不需要重载该方法。 Just use the so called variable arguments . 只需使用所谓的variable arguments The are available in Java since version 1.5. 从1.5版开始,它们在Java中可用。 For example: 例如:

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

You can use the method in two ways: 您可以通过两种方式使用该方法:

  1. Pass the array itself. 传递数组本身。 Like this: 像这样:

    init(array); 的init(数组);

  2. Pass each of the array elements. 传递每个数组元素。 Like this: 像这样:

    init(array[0], array[1], ... array[n]); 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. 您始终可以使用变量arguments方法参数。 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. 这使条件成为int [],您可以迭代它以获得初始条件。

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

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