1

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
4
  • In your code you basically have a List<HashMap<Long, Int>> now. I don't think that's what you want. You probably either want to have a HashMap<Long, Int> or a List<Pair<Long, Int>>. Commented Mar 18, 2021 at 23:58
  • Please check the edit I added to the question Commented Mar 19, 2021 at 0:09
  • check my first code snippet. It creates an empty hashmap and afterwards adds values to it. Commented Mar 19, 2021 at 0:10
  • 1
    "Coming from PHP" - there's your problem. Commented Mar 19, 2021 at 13:29

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok bla.get(0) is showing me [(7, 2), (7, 2)] but how to specifically get the int and the long?
Do you use the hashmap or the list variant?
Oh nvm it actually works, for what ever reason Android Studio cached the old prints and printed them out instead of the new results, needed to clear cache and run again. Thanks!
0

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 } ]

Comments

0

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

2 Comments

bla[1].first is giving me the entire bla??
Your solution works too so I upvoted, there was a problem with android studio

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.