[英]Using a helper function in Java to get an index in an array (no parameters)
[英]Get an array index from a list of parameters in Java
我想要一個方法或函數使用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
}
}
public static Object getArrayIndex(Object[] theArray, Integer[] theIndices){
Object result=theArray;
for(Integer index: theIndices) {
result = ((Object[])result)[index];
}
return result;
}
請注意,此(和其他解決方案)不進行邊界檢查,因此您可能會收到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]];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.