从Java中的参数列表中获取数组索引

时间:2013-03-18 20:07:07

标签: java arrays

我想要一个方法或函数来使用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
    }
}

2 个答案:

答案 0 :(得分:0)

public static Object getArrayIndex(Object[] theArray, Integer[] theIndices){
    Object result=theArray;
    for(Integer index: theIndices) {
        result = ((Object[])result)[index];
    }    
    return result;        

}

答案 1 :(得分: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]];
}