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
?
还是有什么主要区别?
or is there any major difference?
推荐答案
两者之间的唯一区别是传达您的意图.
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
的特定于ArrayList
的类似物).
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屋!