Reputation: 21
I don't understand why some elements go missing. My supposition is that I somehow declared my variables wrong. But if not I don't see what is wrong in the conceptualization of the code.
I tried to create an array at the beginning of the function which is supposed to be the same at the end, but the elements are still missing.
(Example :
val savedArray = nameArray
[some code where none of the two arrays are modified]
nameArray = savedArray)
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
var nameArray = arrayListOf("Julia", "Maxime", "Thomas", "Dean", "Samuel")
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.i("Before", "$nameArray") // ["Julia", "Maxime", "Thomas", "Dean", "Samuel"]
val randomArray = choosePlayer()
Log.i("After", "$nameArray") // [Maxime, Dean, Samuel] Where are Thomas and Julia ?
}
fun choosePlayer(): ArrayList<String> {
val endArray = arrayListOf<String>()
var editArray = nameArray
val name1 = editArray.random()
endArray.add(name1)
editArray.remove(name1)
val name2 = editArray.random()
endArray.add(name2)
editArray.remove(name2)
Log.i("return value", "$endArray") // [Thomas, Julia]
return endArray
}
}
I expect the nameArray to be full but instead two elements are always missing. I noticed that they went missing once they are removed from editArray.
Upvotes: 1
Views: 219
Reputation: 4753
ArrayList
is mutable type. As @Blackbelt mentioned you assigned endArray
and editArray
to the same value.
So, what I would like to add to that answer is to suggest more "kotlin-like" solution - use unmutable collections. It's easier to predict what will happen in your code.
val nameArray = listOf("s1", "s2", "s3") // You cannot modify content of this list.
fun choosePlayer(): List<String> {
return nameArray.shuffled().subList(0, 2)
}
method .shuffled()
creates a copy of collection and doesn't modify content of original collection. So, you can be always sure that nameArray
created as listOf<T>
(which returns List<T>
) will always have the same content.
If you need modify collection there is a way to do following:
val list = listOf(...)
// Create a mutable copy of list.
// Whatever you do with that list you will not modify original list.
val mutable = list.toMutableList()
Upvotes: 0
Reputation: 157437
I expect the nameArray to be full but instead two elements are always missing.
It is because endArray and editArray are the same object. Here
val endArray = arrayListOf<String>()
var editArray = nameArray
editArray
and endArray
are the same reference. Just create a new one
val endArray = arrayListOf<String>()
var editArray = arrayListOf<String>()
Upvotes: 1