Kotlin中ArrayList< String>()和mutableListOf< String>()之间的区别 [英] Difference between ArrayList<String>() and mutableListOf<String>() in Kotlin

查看:1088
本文介绍了Kotlin中ArrayList< String>()和mutableListOf< String>()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private val repositories = mutableListOf<String>()

private val repositories = ArrayList<String>()

都是可变列表,那么两个关键字mutableListOfArrayList的意义是什么?

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&lt; String&gt;()和mutableListOf&lt; String&gt;()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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