2013-03-18 53 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]]; 
}