What would be the equivalent in Java of `Array<...
# getting-started
k
What would be the equivalent in Java of
Array<IntArray>
? I'm trying to store a 2D matrix of ints/floats in a compact way, would this Array of IntArrays be the way to go? Would that be equivalent to
int[][]
?
👌 4
j
If you want to be equivalent, yes that's what this is. However, if accesses to this structure are performance sensitive, you might want to consider a 1-dimensional int array instead (using
i * width + j
indexing to map to 2D). This avoids pointer indirections
k
yeah, I think I misunderstood how Java lays out
int[][]
in memory - it's not a one continuous chunk of memory, it's array of pointers to arrays with continous memory?
👌 1
I thought Java did something Kotlin can't... actually, Java doesn't do it as well (probably will with Valhalla)
I think I'll try going with a one large
int[]
array and do the indexing myself...
thanks!
j
Yes exactly, Java and Kotlin have the same capabilities in this respect, you have to manually handle your 1D array if you want contiguous memory
👍 1
y
Just saying, you can very easily create a
@JvmInline value class 2DIntArray
that under the hood uses a normal
IntArray
and lays out the 2d matrix in a continuous block of memory so that it's still efficient but all the indexing for getting and setting are hidden away in the value class
5
j
Of course the smart indexing needs to be abstracted away
y
Yeah I'm just saying that a value class will make that invisible to any consumer of the array
👍 1
t
just a little hint on the side: you could write an extension for the get-operator function on
IntArray
(or some wrapper class if you prefer) that accepts 2 parameters. Of course this would require you to know the "width" of your matrix, but it could look something like this:
Copy code
operator fun IntArray.get(x: Int, y: Int) = get(y * width + x)
That way you could call
my2DArray[x, y]
👍 1