java更改特定键的值也会更改其他键的值
这就是我生成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))
}
这会改变这对的第二个值
override fun onShiftChange(pos: Int, datePos: Int, shift: String) {
val pair = Pair(staffList[pos].third[datePos].first, shift)
staffListUpdated[pos].third[datePos] = pair
}
但是相反,它会更改pos中的其他值,也就是说,如果我更改statflistupdated[0]。第三个[0]=配对它会改变staffListUpdated[1]。第三[0]=也有一对。我试了很多方法,但都没用
[
{
"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"
}
]
}
]
# 1 楼答案
在
对于每个
Triple
都使用相同的列表实例这意味着如果你得到你的一个
Triple
的列表,并且改变了一些东西,那么你每改变一次Triple
一种解决方案是在插入或修改时复制列表
你还需要做一份清单的深度副本。因为如果你做了一个列表的浅拷贝,
Pair
的实例仍然是相同的,如果你改变了其中一个,你就会(再次)为每个Triple
改变它