Kotlin- Kotlin List filter是否会创建一个新列表对象?
fun main() {
var list1 = listOf("AAAA", "ASAS", "ADDAD", "AS")
var list2 = list1
println(list2 === list1)
list2 = list2
.filter { it.length >= 3 }
println(list2 === list1)
}
上面代码的输出是:
true
false
但是我很困惑为什么list1没有被修改,因为List1和List2首先引用了同一列表对象。谁能帮助我了解这里到底发生了什么?
fun main() {
var list1 = listOf("AAAA", "ASAS", "ADDAD", "AS")
var list2 = list1
println(list2 === list1)
list2 = list2
.filter { it.length >= 3 }
println(list2 === list1)
}
The output of above code is:
true
false
But I am confused why list1 is not being modified since both list1 and list2 are referencing to same list object first. Can anyone please help me understand what exactly is going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确实,
过滤器
确实创建了一个新列表。当您这样做时,
您将新列表分配给
list2
,所以现在list2
停止参考list1 引用,并开始参考由
filter
创建的列表。因此,list2
和list1
现在是指不同的东西。Indeed,
filter
does create a new list.And when you do
you are assigning that new list to
list2
, so nowlist2
stops referring to whatlist1
refers to, and starts to refer to the list that was created byfilter
instead. Therefore,list2
andlist1
now refers to different things.