在Java中缩放数组维度



我想制作一个方法,可以接收n个维度的数组,然后对这些信息进行排序。排序部分不在这个问题的范围内,因为我所关注的部分是让一个方法接受n维的数组。通常情况下,您会将int[]nums之类的内容作为参数。然而,这不允许可缩放的维度输入。我做了一些研究,下面的代码准确地计算了一个数组的维数,但我不确定该从哪里开始,因为我不知道如何从一个对象初始化一个n维的数组。

public static int dimensionOf(Object arr) {
int dimensionCount = 0;
Class<?> c = arr.getClass(); // getting the runtime class of an object
while (c.isArray()) { // check whether the object is an array
c = c.getComponentType(); // returns the class denoting the component type of the array
dimensionCount++;
}
return dimensionCount;
}

这里还有一些东西来解释我的问题,比如说有人把二维数组作为对象。如果发生这种情况,我的维度变量将等于2,因为它使用上面的代码来确定数组的维度。我一直在想如何生成一个可用的变量。在这里,你可以看到我试图将对象(我知道它是数组的一个实例(转换为1d数组,这将通过一个错误,因为传入的对象是2d数组。

public static int sortNDimensionalArray(Object obj) {
int dimensions = dimensionOf(obj);
//This means we did not get an array passed in
if(dimensions == 0) return -1;
int[] array = (int[]) obj;
return 1;
}

我试过了,得到了它,它对我有效:

public static int dimensionOf(Object... args) {
int dim = 0;
Class<?> c = args.getClass();
while(c.isArray()) {
c = c.getComponentType();
dim++;
}
return dim;
}

最新更新