问题描述
在Java中,不同维度的阵列具有不同的类型。所以这需要一个方法 INT []
作为参数不能采取 INT [] []
或 INT [] [] []
。我有很多code的,我创建的十分相似,但对数组的维数的方法。有没有一种方法来处理任意维数组,从而抽象出这个共同的功能?
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?
推荐答案
如果你愿意放弃类型安全,你可以用一个小的递归这样做(在这里没有惊喜,不是吗?)和反射。
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.
下面是一个快速演示:
import java.util.*;
import java.lang.*;
import java.lang.reflect.Array;
class Main {
public static int sumArray(Object array) {
Class type = array.getClass();
if (!type.isArray()) {
throw new IllegalArgumentException("array");
}
Class ct = type.getComponentType();
int res = 0;
int len = Array.getLength(array);
if (ct.isArray()) {
for (int i = 0 ; i != len ; i++) {
res += sumArray(Array.get(array, i));
}
} else {
for (int i = 0 ; i != len ; i++) {
res += Array.getInt(array, i);
}
}
return res;
}
public static void main (String[] args) throws java.lang.Exception
{
int[] a = new int[] {1,2,3,4,5,6,7,8,9,10};
int aa[][] = new int[][] {{1,2},{3,4},{5,6}};
int aaa[][][] = new int[][][]{{{1,2},{3,4},{5,6}},{{7,8},{9,10},{11,12}}};
System.out.println(sumArray(a));
System.out.println(sumArray(aa));
System.out.println(sumArray(aaa));
}
}
这篇关于在抽象Java数组的维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!