I'm having an issue where I assign a variable based on data that is being received from a server (in JSON). I have two class variables
- teams - which will be changed based on user interaction
- reset_teams - which should always stay the same as the original list so that a user can reset all values whenever they choose.
These variables are used to (re-)populate a RecyclerView at various times based on user interaction (i.e., pressing a button inside of the app)
My problem is that any time I make a change to an object in the teams ArrayList, it also makes a change to the reset_teams ArrayList, as if they are somehow connected (similar to pass by value/reference in a function).
I am somewhat new to Kotlin, so it's quite possible I am missing something, but I'm wondering how I can keep the reset_teams ArrayList exactly the same at all times, even if the teams ArrayList has changes to different properties of the objects it stores?
// Class variables
var teams: ArrayList<myObject> = ArrayList()
var reset_teams: ArrayList<myObject> = ArrayList()
// Function to handle JSON after receiving data from remote server
private fun handleJson(jsonString: String?) {
val jsonArray = JSONArray(jsonString)
val list = ArrayList<myObject>()
var x = 0
while (x < jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(x)
list.add(
myObject(// a bunch of code to make an object of type myObject)
)
x++
}
teams = list
reset_teams = list
test() // Change a property
}
private fun test(){
teams[0].someProperty = 10
println(teams) // The someProperty of the first element of the ArrayList has been correctly assigned to 10
println(reset_teams) // The someProperty of the first element of the ArrayList has been changed to 10 even though the reset_teams was never assigned a new value
}