我试着学习用Android做事情的"Kotlin原生方式“,而不是Kotlin、Java和Android开发方面的专家。具体来说,何时使用与 MutableList.
在我看来, should be chosen whenever possible。然而,如果我看一下安卓的例子,他们似乎总是选择ArrayList (据我所知)。
下面是一个使用ArrayList并扩展RecyclerView.Adapter的工作示例的片段。
class PersonListAdapter(private val list: ArrayList<Person>,
private val context: Context) : RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {问题1)
我是否可以简单地按照下面的方式编写上面的代码(注意MutableList<>而不是ArrayList<>),即使我是在借用Android代码呢?
class PersonListAdapter(private val list: MutableList<Person>,
private val context: Context) : RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {问题2)
总是在ArrayList上使用ArrayList真的更好吗?主要原因是什么?我上面提供的一些链接超出了我的考虑,但在我看来,MutableList是一个更宽松的实现,将来更有能力进行更改和改进。是那么回事吗?
发布于 2019-04-06 02:22:39
区别是:
ArrayList(),您将显式地说:“我希望这是MutableList的一个ArrayList实现,永远不要更改为其他任何东西”。mutableListOf(),这就像说“给我默认的MutableList实现”。当前MutableList (mutableListOf())的默认实现返回ArrayList。如果将来(不太可能)这种情况发生变化(如果设计了一个新的更有效的实现),那么这种情况可能会变成...mutableListOf(): MutableList<T> = SomeNewMoreEfficientList()。
在这种情况下,在代码中使用ArrayList()的地方,它将保持为ArrayList。无论您在何处使用了mutableListOf(),这都将从ArrayList更改为名为SomeNewMoreEfficientList的出色名称。
发布于 2018-11-09 01:30:31
ArrayList是Kotlin中MutableList接口的一个实现:
class ArrayList<E> : MutableList<E>, RandomAccesshttps://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。
https://stackoverflow.com/questions/53218501
复制相似问题