Reputation: 13
I have some issues with creating a ByteArray
var where its elements are also ByteArray
, I don't know is it possible first ? and how to ?
Upvotes: 1
Views: 4929
Reputation: 9434
A ByteArray
is just what it sounds like, an array of bytes. If you want to hold onto multiple byte arrays you can use a generic list or array.
Something like this:
// say you have three byte arrays
val ba1 = ByteArray(3) { it.toByte() }
val ba2 = ByteArray(3) { (it + 3).toByte() }
val ba3 = ByteArray(3) { (it + 6).toByte() }
// make a list of them like so
val allByteArray = listOf(ba1, ba2, ba3)
Based on your more recent comment it seems you may want to add to allByteArray in a loop, if that is the case you can also use an ArrayList
like this:
val allByteArray = ArrayList<ByteArray>()
for (i in 0 until 3) {
// some byte array
val ba = ByteArray(3) { (it + (i*3)).toByte() }
// add to list
allByteArray.add(ba)
}
Also as suggested by Alexey Romanov, you could do this in the constructor for a MutableList
(or the same thing can be done with a list if it doesn't need to be mutable) like this:
val allByteArray = MutableList(3) { i ->
ByteArray(3) { (it + (i*3)).toByte() }
}
Upvotes: 3
Reputation: 93609
Maybe you're looking for a 2D array of Bytes? You can create an Array of ByteArrays:
val array = Array(3){ByteArray(3)}
array[0][1] = 3 // for example
or to initialize it as you declare it:
val array = arrayOf(
byteArrayOf(0, 1, 2),
byteArrayOf(3, 4, 5),
byteArrayOf(6, 7, 0)
)
In Java this would be:
byte[][] array = new byte[3][3];
// or
byte[][] array = {
{0, 1, 2},
{3, 4, 5},
{6, 7, 0},
}
Upvotes: 2