Is it possible to make the method run differently depending on the length of the transmitted array (0, 1, 2 or 3)? And solve this problem with overload.

Those. in each case, we actually transfer a different number of parameters from 0 to 3.

I pass an array whose length varies from 0 ( null ) to 3 elements. Depending on the length of the transmitted array, the method varies slightly.

While I thought up foolishly:

 if (currOper.length == 0) { expVal = expValDet(); } if (currOper.length == 1) { expVal = expValDet(currOper[0]); } if (currOper.length == 2) { expVal = expValDet(currOper[0], currOper[1]); } 
  • so the количество параметров от 0 до 3-х or the длины передаваемого массива 0 1 2 3 ? Maybe more specific? - Alexey Shimansky
  • most likely it refers to the parameters of the array, the author did not correctly put it. - Flippy
  • I added a little specifics in the question. - lmihael
  • You know, I agree with @AlekseyShimansky about the XY-problem: you would not have met such a task in real production tasks, but your task looks like too educational, training. Often swich (your few if - this switch) is converted into classes, see for example here, but this is an ambiguous practice, and well, they don’t do it based on the length of the array. - AK

1 answer 1

In Java, it is not possible to specify in the method parameters that the array should be of the specified length. Therefore, it will not be possible to overload the method by specifying an array of a different length in the overload.

Alternatively, you can transfer the elements of the array separately:

 public void method(int i1, int i2, int i3, int i4) { ... } public void method(int i1, int i2, int i3) { ... } 

You can also not overload the method, but create different methods:

 public void methodFour(int[] data) { ... } public void methodThree(int[] data) { ... } 

However, in both cases, you still have to check the length of the array and call one or another method in an if-else or switch-case .

  • one
    It's a pity. In both cases, the code looks ugly. Anyway, thanks for the reply. - lmihael
  • one
    @lmihael it seems to me personally that this is a problem XY - Alexey Shimansky
  • 2
    @lmihael on health. Yes, ugly. However, you can make these methods private , and only show one option to the outside world, public void method(int[] array) , within which you already need to call the required private method. - Regent
  • I mean, ugly? And a pack of "overloaded" methods than this would be different? - vp_arth
  • @vp_arth ultimately, none of the options, including a bundle of congestion, elegance is different. But, of course, this does not negate the fact that such structures are used with a small number of parameters. - Regent