Search code examples
javaarraysmultidimensional-arrayarray-indexing

Indexing multidimensional array


Is it possible in Java to index an Array somehow like arr1[arr2] if arr1 is an int[][] and arr2 an int[2].

I would like a better way to achieve the same as arr1[arr2[0]][arr2[1]] which looks really awfull. And by better I mean easier to read and understand.


Solution

  • Is it possible in Java to index an Array somehow like arr1[arr2] if arr1 is an int[][] and arr2 an int[2]

    arr1[arr2] is not valid if arr2 is an int[]. The only thing that can go in between the square brackets is a number (or a variable that references the number). arr1[arr2[0]] is valid (assuming both arrays have at least 1 element in them) because arr2[0] would be an int.

    EDIT

    After I posted this answer the question was changed to include "Edit: I want to achieve the same as arr1[arr2[0]][arr2[1]]".

    The way to achieve what you have shown, is exactly what you have shown, assuming arr1 is a int[][], arr2 is a int[], arr1 has at least 1 element in the first dimension and its value is an array that has at least 2 elements.

    2nd EDIT

    You said "I would like a better way for achieving arr1[arr2[0]][arr2[1]]". "better" is subjective. if you want better in terms of fewer lines of code, it won't get better because you have the minimum lines of code (1). If you want it to be easier to read, you could do something like this:

    // of course, knowing the nature of the data
    // would allow better variable names...
    int firstElementInArr2 = arr2[0];
    int secondElementInArr2 = arr2[1];
    int[] outerArray = arr1[firstElementInArr2];
    int result = outerArray[secondElementInArr2];