Reputation: 3
This is how I generate dutyList.
val dutyList = ArrayList<Triple<Int, String, ArrayList<Pair<String, String>>>>()
val dateShiftPair = ArrayList<Pair<String, String>>()
dateList.forEach {date ->
dateShiftPair.add(Pair(date, "E"))
}
staffList.forEach {staff ->
dutyList.add(Triple(list.indexOf(staff), staff.name!!, dateShiftPair))
}
And this should change the second value of the pair
override fun onShiftChange(pos: Int, datePos: Int, shift: String) {
val pair = Pair(staffList[pos].third[datePos].first, shift)
staffListUpdated[pos].third[datePos] = pair
}
but instead it changes other values in pos, that is if I change staffListUpdated[0].third[0] = pair it changes staffListUpdated[1].third[0] = pair as well. I tried many ways but nothing helped.
[
{
"first": 0,
"second": "Ralph",
"third": [
{
"first": "3/5",
"second": "G" //change should happen here only
},
{
"first": "4/5",
"second": "E"
},
{
"first": "6/5",
"second": "E"
}
]
},
{
"first": 1,
"second": "Mike",
"third": [
{
"first": "3/5",
"second": "G" //but change happens here as well.
},
{
"first": "4/5",
"second": "E"
},
{
"first": "5/5",
"second": "E"
}
]
}
]
Upvotes: 0
Views: 232
Reputation: 3508
In
staffList.forEach {staff ->
dutyList.add(Triple(list.indexOf(staff), staff.name!!, dateShiftPair))
}
you use for every Triple
the same list instance.
This means if you get the list of one of your Triple
s and change something you change it for every Triple
.
A solution is to copy the list either on insertion or on modification.
You also need to do a deep copy of the list. Because if you make a shallow copy of the list the instances of the Pair
s are still the same and if you then change one of them you change it (again) for every Triple
.
Upvotes: 1