Reputation:
Coming from PHP it's beyond annoying to deal with all kind of array types in Kotlin/Java like listOf
mutableListof
arrayOf
mutableArrayOf
etc
I just want be able to add values (hashMapOf
) to a damn array
.
After initializing array
(if it's even an array or what ever):
val bla = mutableListOf(hashMapOf<Long, Int>())
I tried those:
bla.add(5L to 7)
bla.add(5L, 7)
bla += 5L to 7
how to do this right??
What I basically want:
val bla = array()
bla.add(4L, 7)
bla.add(5L, 8)
bla.add(6L, 9)
and then:
Log.d("tag", "get long from second: " + bla[1].getTheLong) // 5L
Log.d("tag", "get int from second: " + bla[1].getTheInt) // 8
Upvotes: 1
Views: 269
Reputation: 3476
From you edit it becomes clear you want
val blah = mutableListOf<Pair<Long, Int>>()
blah.add(Pair(4L, 7))
blah.add(Pair(5L, 7)) // equivalent to blah.add(5L to 7)
and then
Log.d("tag", "get long from second: " + bla[1].first) // 5L
Log.d("tag", "get int from second: " + bla[1].second) // 8
Upvotes: 0
Reputation: 1741
Currently, in your code, bla
is a List<HashMap<Long, Int>>
.
I guess you want to have a HashMap<Long, Int>
, which would result in this:
val bla = mutableMapOf<Long, Int>()
bla.put(7, 2);
print(bla.get(0))
or you want to have a List<Pair<Long, Int>>
, which results in this:
val bla = mutableListOf<Pair<Long,Int>>()
bla.add(Pair(7, 2))
print(bla.get(0))
The difference is, that for a map each key must be unique. The list of pairs allows you to add multiple pairs that are equal.
Upvotes: 1
Reputation: 58563
Try the following solution:
fun main() {
val bla = mutableListOf(hashMapOf<Long, Int>())
bla[0][0] = 5
bla[0][1] = 7
println(bla)
}
// Result: [ { 0=5, 1=7 } ]
Upvotes: 0