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.
arr1[arr2]
is not valid ifarr2
is anint[]
. 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) becausearr2[0]
would be anint
.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 aint[][]
,arr2
is aint[]
,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: