In Java, arrays of different dimensionalities have different types. So a method that takes int[] as a parameter cannot take int[][] or int[][][]. I have a lot of code where I create methods that are quite similar but for the dimensionality of the array. Is there a way to handle arrays of arbitrary dimensionality, and thus abstract out this common functionality?
In Java, arrays of different dimensionalities have different types. So a method that takes
Share
If you are willing to forego type safety, you can do it with a little recursion (no surprise here, right?) and reflection.
The idea is to write your method in a way that it recurses down until the array has only one dimension. Once you’re at the single-dimension level, do the work; otherwise, call yourself recursively, and aggregate your findings from the prior levels if necessary.
Here is a quick demo: