gpt4 book ai didi

kotlin - 对象引用更改原始对象

转载 作者:行者123 更新时间:2023-12-02 13:09:27 25 4
gpt4 key购买 nike

class Adult: Resident {
constructor(name: String, id:String): super(name, id)
var email: String? = null
var address: MutableList<String>? = null

fun setAddress(s: String){
address = s.split("\\n".toRegex()).toMutableList()
}

}

它使该测试用例失败,因为
b.address = a.addressb.address?.add("Universe")也被添加到对象 a中。
fun test6() {
val a = Adult("Roger Widdoff","604119274")
val b = Adult("Kathleen Craig","647022192")
a.setAddress("123 Main Street\nAnytown, Country")
assertEquals(2,a.address?.size)

b.address = a.address

b.address?.add("Universe")

assertEquals(3,b.address?.size)

assertEquals(2,a.address?.size)
}

我真的很困惑为什么会发生这种情况,而且我已经搜索了数小时的文档。谁能在某个地方链接我以解决此问题?谢谢。

最佳答案

使用b.address = a.address,您可以创建一个指向现有对象实例的变量(将其视为指向存储对象实例的指针)。它不是在创建副本。结果,您有两个变量b.addressa.address指向同一个对象MutableList<String>的实例。无论您使用哪个变量,对此实例所做的任何更改都将在两个实例中均可见。

这不是Kotlin的“功能”,它是一个一般概念,称为Aliasing:

In computing, aliasing describes a situation in which a data location in memory can be accessed through different symbolic names in the program. Thus, modifying the data through one name implicitly modifies the values associated with all aliased names, which may not be expected by the programmer.



通常,我建议您将列表的类型更改为readonly List,这样一开始就可以避免出现此错误的测试用例。由于您无法修改测试用例,因此可以使用创建列表副本的自定义 setter/getter 来解决该问题:
var address: MutableList<String>? = null
get () = field?.toMutableList()

关于kotlin - 对象引用更改原始对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48920801/

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