【问题标题】:Changing value of specific key changes the value of other keys as well更改特定键的值也会更改其他键的值
【发布时间】:2021-04-29 22:19:20
【问题描述】:

这就是我生成 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 中的其他值,也就是说,如果我更改 staffListUpdated[0].third[0] = pair 它会更改 staffListUpdated[1 ].third[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"
      }
    ]
  }
]

【问题讨论】:

  • 这不会编译
  • 可能是因为Pair的equals方法在list上调用indexof的时候没有比较里面的key
  • 但无论如何,你为什么不使用地图(hashmap)而不是其中包含对的列表
  • Hashmaps 更快,您可以轻松地使用 containsKey() 找出存在的键
  • 您的代码使用相同的列表实例作为所有三元组的第三个值。

标签: java kotlin arraylist key-value


【解决方案1】:

staffList.forEach {staff -> 
     dutyList.add(Triple(list.indexOf(staff), staff.name!!, dateShiftPair))
}

您为每个Triple 使用相同的列表实例。

这意味着,如果您获得 Triples 之一的列表并更改某些内容,则您会为每个 Triple 更改它。

解决方案是在插入或修改时复制列表。

您还需要对列表进行深层复制。因为如果您制作列表的浅表副本,Pairs 的实例仍然是相同的,如果您随后更改其中一个,您将(再次)为每个 Triple 更改它。

【讨论】:

    猜你喜欢
    • 2018-12-03
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多