【发布时间】:2014-08-18 08:31:37
【问题描述】:
假设我们有一个多维数组,并且维数只有在运行时才知道。假设我们有整数个索引。
如何对数组应用索引以访问数组的元素?
更新
假设:
int [] indices = new int { 2, 7, 3, ... , 4}; // indices of some element
int X = indices.length; // number of dimensions
Object array = .... // multidimensional array with number of dimensions X
...
我想从array 获取索引indices 寻址的元素。
更新 2
我基于递归编写了以下代码:
package tests;
import java.util.Arrays;
public class Try_Multidimensional {
private static int element;
public static int[] tail(int[] indices) {
return Arrays.copyOfRange(indices, 1, indices.length);
}
public static Object[] createArray(int ... sizes) {
Object[] ans = new Object[sizes[0]];
if( sizes.length == 1 ) {
for(int i=0; i<ans.length; ++i ) {
ans[i] = element++;
}
}
else {
for(int i=0; i<ans.length; ++i) {
ans[i] = createArray(tail(sizes));
}
}
return ans;
}
public static Object accessElement(Object object, int ... indices) {
if( object instanceof Object[] ) {
Object[] array = (Object[]) object;
return accessElement(array[indices[0]], tail(indices));
}
else {
return object;
}
}
public static void main(String[] args) {
element = 0;
Object array = createArray(4, 5, 12, 7);
System.out.println(accessElement(array, 0, 0, 0, 0));
System.out.println(accessElement(array, 0, 0, 0, 1));
System.out.println(accessElement(array, 1, 0, 10, 0));
try {
System.out.println(accessElement(array, 0, 5, 0, 1));
}
catch(Exception e) {
System.out.println(e.toString());
}
System.out.println(4*5*12*7-1);
System.out.println(accessElement(array, 3, 4, 11, 6));
}
}
问题是:
1) 有没有来自 JDK 和/或著名库的可靠现成方法?
2) 我使用的是Object。可以避免吗?我可以创建/访问内置或特定类型的可变维度数组吗?使用Object 的回报有多大?
【问题讨论】:
-
您能否说得更具体一点,也许提供一个代码片段?
-
你能举个例子吗。看不懂
-
我建议你阅读this。
-
java中没有多维数组..它是数组的数组..
-
@Anirudha 我建议你也阅读我提供的链接...
标签: java arrays multidimensional-array