https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

Karlo Lozovina

09/16/2021, 3:10 PM
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

Joffrey

09/16/2021, 4:02 PM
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

Karlo Lozovina

09/16/2021, 4:05 PM
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

Joffrey

09/16/2021, 4:08 PM
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

Youssef Shoaib [MOD]

09/16/2021, 5:02 PM
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

Joffrey

09/16/2021, 5:29 PM
Of course the smart indexing needs to be abstracted away
y

Youssef Shoaib [MOD]

09/16/2021, 6:46 PM
Yeah I'm just saying that a value class will make that invisible to any consumer of the array
👍 1
t

Tobias Berger

09/17/2021, 7:30 AM
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