0

我想要一个方法或函数来使用 Java 中的索引数组获取数组的元素,但我还不确定如何做到这一点。是否可以从 Java 中的参数数组中获取数组索引(这样getArrayIndex(theArray, [0, 1])会返回theArray[0][1]?

import java.util.*;
import java.lang.*;
class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Object[][] theArray = {{"Hi!"}, {"Hi!"}, {"Hi!", "Hi!"}};
        Object index1 = getArrayIndex(theArray, [0, 0]) //this should return theArray[0][0]
        Object[] index1 = getArrayIndex(theArray, [0]) //this should return theArray[0]
    }

    public static Object getArrayIndex(Object[] theArray, Object[] theIndices){
        //get the object at the specified indices
    }
}
4

2 回答 2

0

请注意,此(和其他解决方案)不进行边界检查,因此您可能会得到 IndexOutOfBounds 异常。

// returns the Object at the specified indices
public static Object getArrayIndex(Object[][] theArray, int[] theIndices) {
   if (theIndices.length > 1) {
     return theArray[theIndices[0]][theIndices[1]];
   }
   return theArray[theIndices[0]];
}
于 2013-03-18T21:03:59.040 回答
0
public static Object getArrayIndex(Object[] theArray, Integer[] theIndices){
    Object result=theArray;
    for(Integer index: theIndices) {
        result = ((Object[])result)[index];
    }    
    return result;        

}
于 2013-03-18T20:11:16.817 回答