Skip to content
Advertisement

Method Overloading Techinques

I have a method overload that goes as follows:

JavaScript

My question is there a way to condense the solution to have one method that takes into account N-Dimensional Arrays. The code runs fine like this however, I would like to know what Java techniques can help account for the increase in dimensions. I would like to add some details and that is that the first method is the base method, and all the other methods call that first int[] a. The new section I added is the full code I am currently in developing this code which my professor gave as a challenge. I currently have the Data Structures by Lang, and I can accept hints. I prefer hints actually because I would like to learn to code this.

Advertisement

Answer

When the parameter is amulti dimensional array, you can recursively call the function that digs down until you end up with a 1d array of numbers. The logic is:

JavaScript

I have 2 functions. One that takes a variable number of args, and a recursive one. The first just calls the second with the var args as an array. The varargs function needs a bit of work if you want to allow mixed parameters (eg: countOdd(new int [] {1,2,3}, 4, 5);)

JavaScript

As mentioned in the comments, this will not work for primitive data types (ex: int, etc). Instead, use non-primitive types (ex: Integer, etc).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement