我既是Kotlin,Java也不是Android开发方面的专家,我正在尝试学习“ Kotlin本机方式”来在Android中做事。具体来说,何时使用ArrayList
与MutableList
。
在我看来,MutableList
should be chosen whenever possible。但是,如果我看一下Android示例,它们似乎总是选择ArrayList
(据我到目前为止发现的那样)。
下面是使用ArrayList
并扩展Java的RecyclerView.Adapter
的工作示例的片段。
class PersonListAdapter(private val list: ArrayList<Person>,
private val context: Context) : RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {
即使我是从Android的Java代码中借用的,我也可以简单地按如下方式编写上面的代码(请注意,MutableList<>
而不是ArrayList<>
)。
class PersonListAdapter(private val list: MutableList<Person>,
private val context: Context) : RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {
始终在MutableList
上使用ArrayList
真的更好吗?主要原因是什么?我上面提供的某些链接使我难以忘怀,但是在我看来MutableList
是一个较宽松的实现,将来更有能力进行更改和改进。是吗?
答案 0 :(得分:3)
ArrayList是Kotlin中MutableList接口的实现:
class ArrayList<E> : MutableList<E>, RandomAccess
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/index.html
该答案可能表明应尽可能选择MutableList,但是ArrayList 是MutableList。因此,如果您已经在使用ArrayList,则实际上没有理由使用MutableList,特别是因为您实际上不能直接创建它的实例(MutableList是接口,而不是类)。
实际上,如果您查看mutableListOf()
Kotlin扩展方法:
public inline fun <T> mutableListOf(): MutableList<T> = ArrayList()
您会看到它只返回您提供的元素的ArrayList。
答案 1 :(得分:1)
区别是:
如果您使用ArrayList()
,则明确表示“ 我希望这是ArrayList
的{{1}}实现,不要更改为任何其他 ”。
如果您使用MutableList
,就像说“ 给我默认的mutableListOf()
实现”。
MutableList
(MutableList
)的当前默认实现返回mutableListOf()
。如果将来(不太可能)发生这种情况(如果设计了一种新的更有效的实现方式),它可能会更改为ArrayList
。
在这种情况下,无论您在代码中使用了...mutableListOf(): MutableList<T> = SomeNewMoreEfficientList()
的哪个位置,它都将保留ArrayList()
。无论您在何处使用过ArrayList
,它都会从mutableListOf()
变成醒目的ArrayList
。