2013-03-18 51 views
0

我想要一个方法或函数来使用Java中的索引数组获取数组的元素,但我不确定如何执行此操作。是否有可能从参数Java中的数组获取数组索引(这样getArrayIndex(theArray, [0, 1])将返回theArray[0][1]从Java中的参数列表中获取数组索引

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 
    } 
} 
+0

System.arraycopy(java.lang.Object中,INT,java.lang.Object中,INT,INT)应该有所帮助。 – 2013-03-18 20:08:53

+0

我假设你想要的签名是'公共静态对象getArrayIndex( Object [] [] theArray,Object [] theIndices){'(或者甚至更好,'pub lic静态对象getArrayIndex(Object [] [] theArray,int [] theIndices){')? – Noyo 2013-03-18 21:05:54

回答

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

} 
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]]; 
}