首页 > 解决方案 > List 和复制的 MutableList 的区别

问题描述

我将 List 类型变量复制到 MutableList 类型的新变量中,

然后更新新项目的价值。

但是 origin 变量也被更新了。

这些指向同一个地址吗?

为什么?

var foodList = listOf(
    FoodModel("curry", 2000)
    FoodModel("rice", 1000)
)


// copyed foodList to new variable MutableList<FoodModel> type
val tempList = foodList as MutableList<FoodModel>

Log.e("weird", tempList[position].name+" "+tempList[position].price)
Log.e("weird", foodList[position].name+" "+foodList[position].price)
//E/weird: rice 1000
//E/weird: rice 1000


tempList[position] = FoodModel(nameEdit.text.toString(), priceEdit.text.toString().toInt())


Log.e("weird", tempList[position].name+" "+tempList[position].price)
Log.e("weird", foodList[position].name+" "+foodList[position].price)
//E/weird: rice 3333
//E/weird: rice 3333

标签: androidkotlin

解决方案


这些指向同一个地址吗?

是的,因为foodList as MutableList<FoodModel>不是复制,它是类型转换,它可能导致 a ClassCastExceptionor UnsupportedOperationException。要复制列表,请使用toMutableList()

val tempList = foodList.toMutableList()

推荐阅读