android - 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
解决方案
这些指向同一个地址吗?
是的,因为foodList as MutableList<FoodModel>
不是复制,它是类型转换,它可能导致 a ClassCastException
or UnsupportedOperationException
。要复制列表,请使用toMutableList()
val tempList = foodList.toMutableList()
推荐阅读
- glsl - 不正常处理obj文件
- python -
, ValueError("could not convert string to float: 'X'"), - javascript - 无法 npm 链接本地依赖项
- c# - 尝试从 ASP.NET Core 5 Web 应用程序运行 Api 控制器功能时找不到 404
- visual-studio - 始终在 Visual Studio 的成员列表中显示所有成员
- swift - 如何获得分数的完整值而不是在 Swift 中使用 e 接收它?
- python - 我将如何将 tkinters“colorchooser”模块的输出更改为枕头可用的 RGB 代码
- php - 使用 MariaDB 在 JSON_CONTAINS() 中未考虑德语变音符号
- c# - BitConverter 是否错误地处理小端?
- python - OpenCV Good Features to Track 如何设置质量度量?