Kotlin中ArrayList<String>()和mutableListOf<String>()的区别 [英] Difference between ArrayList<String>() and mutableListOf<String>() in Kotlin
问题描述
private val repositories = mutableListOf<String>()
private val repositories = ArrayList<String>()
都是可变列表,那么mutableListOf
或者ArrayList
这两个关键字的意义何在?
Both are mutable list, then what is the point of two keywords mutableListOf
or ArrayList
?
或者有什么主要区别?
推荐答案
两者之间的唯一区别是传达您的意图.
The only difference between the two is communicating your intent.
当您编写 val a = mutableListOf()
时,您是在说我想要一个可变列表,但我并不特别关心实现".相反,当您编写 val a = ArrayList()
时,您是在说我特别想要一个 ArrayList
".
When you write val a = mutableListOf()
, you're saying "I want a mutable list, and I don't particularly care about the implementation". When you write, instead, val a = ArrayList()
, you're saying "I specifically want an ArrayList
".
在实践中,在 Kotlin 编译到 JVM 的当前实现中,调用 mutableListOf
将产生一个 ArrayList
,并且行为没有区别:一旦构建了列表,一切都会一样.
In practice, in the current implementation of Kotlin compiling to the JVM, calling mutableListOf
will produce an ArrayList
, and there's no difference in behaviour: once the list is built, everything will behave the same.
现在,假设 Kotlin 的未来版本将 mutableListOf
更改为返回不同类型的列表.
Now, let's say that a future version of Kotlin changes mutableListOf
to return a different type of list.
更可能的是,Kotlin 团队只有在他们认为新实现对大多数用例更有效的情况下才会做出改变.mutableListOf
然后会让你透明地使用这个新的列表实现,你会免费获得更好的行为.如果这听起来像您的情况,请使用 mutableListOf
.
Likelier than not, the Kotlin team would only make that change if they figure the new implementation works better for most use cases. mutableListOf
would then have you using that new list implementation transparently, and you'd get that better behaviour for free. Go with mutableListOf
if that sounds like your case.
另一方面,也许您花了很多时间思考您的问题,并认为 ArrayList
真的 最适合您的问题,而您没有不想冒险转向次优的东西.那么你可能想直接使用 ArrayList
,或者使用 arrayListOf
工厂函数(一个 ArrayList
特定于 mutableListOf代码>).
On the other hand, maybe you spent a bunch of time thinking about your problem, and figured that ArrayList
really is the best fit for your problem, and you don't want to risk getting moved to something sub-optimal. Then you probably want to either use ArrayList
directly, or use the arrayListOf
factory function (an ArrayList
-specific analogue to mutableListOf
).
这篇关于Kotlin中ArrayList<String>()和mutableListOf<String>()的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!