Hi All. This is my first code snippet. I don't know how practical it is, but I
came up with the idea, so I wanted to do it.
Assuming you have an array. You use a for loop to display its data.
For 2D arrays you use 2 for loops. But that is not dynamic. Every time an extra
dimension is added, you need to write an extra loop. How about a method that
takes as argument an Object, that is actually an array of unknown dimensions (NxD).
By using recursion the program will "generate" dynamically the right amount of
for loops needed to print all the data of the array without having to know how
many dimensions it has.
The first method (printArray(Object obj)), is only to simply demonstration how
is done. We initially check if the object is an array. If yes, we loop it and
we take each of its elements. If that is also an array, we recursively call the
same method. Else we simply print the element itself.
Now because for multidimensional arrays what is printed will not be very well
formatted, a second method was implemented:
printArray(Object obj, int level).
We first call that method with level=0 and for each recursive call we
increase the level. By doing that, we print each dimension/level of the array one extra \t character to the right. The second method prints more information about the array.
And if you want to make sure that the initial call is with level=0 then make that method private and call it from a public method.