dataclass copy with field ArrayList - 改变复制的类的ArrayList 改变原来的 [英] dataclass copy with field ArrayList - change the ArrayList of the copied class changes the original

查看:29
本文介绍了dataclass copy with field ArrayList - 改变复制的类的ArrayList 改变原来的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据类

data class Person(val id: Long = BaseDataContract.BaseData.UNDEFINED_ID.toLong(),
              .....
              val personConsents: ArrayList<PersonConsent> = ArrayList<PersonConsent>()) 

我有两个对象的副本:

person = originalPerson.copy()

然后我更改对象 person 的 personConsents 元素 - 我添加/删除/编辑它们.但是由于某种原因,我发现 originalPerson 对象中发生了我不想发生的相同变化.originalPerson 根本不应该被改变.怀疑 ArrayList 引用有问题,但需要你的建议我能做什么?最后,我需要比较两个对象,例如 fun dataChanged(): Boolean = originalPerson != person 但是当 ArrayList 更改时它不起作用.

Then I change the elements of personConsents for the object person - I add/delete/edit them. But by some reason I see that the same changes are happening in originalPerson object which I don't want to be. originalPerson is not supposed to be changed at all. Suspect there is something with ArrayList references, but need your advice what i can do? At the end I need to compare two objects likefun dataChanged(): Boolean = originalPerson != person bu it doesn't work when ArrayList is changing.

推荐答案

我找到了一个简单的解决方案.我使用我自己的克隆函数为 ArrayList 创建一个新对象并用复制的元素填充它.

I found a simple solution. I use my own clone function which creates a new object for ArrayList and fill it by copied elements.

fun getPersonClone(person: Person): Person {
    val personConsents: ArrayList<PersonConsent> = ArrayList<PersonConsent>()
    person.personConsents.forEach { personConsents.add(it.copy()) }
    return Person(person.id, ......., personConsents)
}

这篇关于dataclass copy with field ArrayList - 改变复制的类的ArrayList 改变原来的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆