gpt4 book ai didi

object - Kotlin .add覆盖MutableList中的所有列表项

转载 作者:行者123 更新时间:2023-12-04 18:26:00 26 4
gpt4 key购买 nike

我有一个包含可变列表的对象

object TrackingEventsList {
var EventDate: String = ""
var EventDescription: String = ""
}

object Waybill {
var WaybillNumber: String = ""
var OriginHub: String = ""
var TrackingEvents: MutableList<TrackingEventsList> = ArrayList()
}

当我尝试添加Waybill.TrackingEvents时,所有以前的实例都将被覆盖并复制最后添加的TrackingEvent。
private fun fillTracking(events: NodeList) {
var list = TrackingEventsList
for (x: Int in 0 until events.length) {
var tName = (events.item(x) as Element).tagName
var event = (events.item(x).firstChild as Text).wholeText
if (tName == "EventDate") {
list.EventDate = event
}
if (tName == "EventDescription") {
list.EventDescription = event
}
}
Waybill.TrackingEvents.plus(list)
}

调用fillTracking 3次后的结果:
Waybill.TrackingEvents[0].EventDescription = "Event3"
Waybill.TrackingEvents[1].EventDescription = "Event3"
Waybill.TrackingEvents[2].EventDescription = "Event3"

最佳答案

由于TrackingEventsList是一个对象,因此它意味着它是一个单例(或只有一个实例)。当您遍历循环时,始终会更新TrackingEventsList对象的同一实例。

TrackingEventsList更改为:

data class TrackingEventsList(var eventDate: String, var eventDescription: String)

每次循环时都创建一个新实例,然后将其添加到列表的末尾:
private fun fillTracking(events: NodeList) {
var eventDate: String = ""
var eventDescription: String = ""
for (x: Int in 0 until events.length) {
val tName = (events.item(x) as Element).tagName
val event = (events.item(x).firstChild as Text).wholeText
if (tName == "EventDate") {
eventDate = event
}
if (tName == "EventDescription") {
eventDescription = event
}
}
Waybill.TrackingEvents.plus(TrackingEventsList(eventDate, eventDescription))
}

关于object - Kotlin .add覆盖MutableList中的所有列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52138831/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com