在 Kotlin 中将元素添加到列表开头的最佳方法是什么 [英] What is the best way to add an element to the beginning of a list in Kotlin

查看:28
本文介绍了在 Kotlin 中将元素添加到列表开头的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的列表

 var foo = mutableListOf("John", "Wayne")

如果我想在列表顶部添加一个元素,到目前为止我正在考虑两个选项.

and if I want to add an element on top of the list, so far I am thinking of two options.

首先:foo.add(0, "Twyla")

第二:foo = (mutableListOf("Twyla") + foo).toMutableList()

我不知道上述两个选项在性能方面的表现如何,但一般推荐的方式是什么?

I am not how the above two options fare in terms of performance but what is a recommended way in general?

推荐答案

这两个选项不太一样:第一个选项只是将一个项目插入到现有可变列表的开头,而第二个创建一个新列表,然后将其转换为另一个新的可变列表.

These two options are not quite the same: the first one just inserts an item into the beginning of the existing mutable list, and the second creates a new list and then converts it into another one new mutable list.

我认为,如果您可以改变现有列表,那么您应该更喜欢第一个选项,因为它比第二个需要更少的内存.

I think if you're fine with mutating the existing list, you should prefer the first option because it requires way less memory than the second one.

这篇关于在 Kotlin 中将元素添加到列表开头的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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