Moosphan / Android-Daily-Interview

:pushpin:每工作日更新一道 Android 面试题,小聚成河,大聚成江,共勉之~

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

2019-07-04:Kotlin中List与MutableList的区别?

Moosphan opened this issue · comments

2019-07-04:Kotlin中List与MutableList的区别?

Ground floor

MutableList:可读写,实际上就是个ArrayList
List:可读 如同Java List一样只是个接口,listof具体怎么实现的只读类我还真不知道

List:有序接口,只能读取,不能更改元素;
MutableList:有序接口,可以读写与更改、删除、增加元素。

Kotlin中List、Set、Map与Java中的List、Set、Map有一些不同,kotlin中为只读,只能访问集合中的内容,不能进行修改操作。
如过需要进行添加修改操作需使用Mutable(可变的)前缀

kotlion中的List是只可读不可写。如果需要读写操作可以用MutableList表示可变的list

只读集合不一定是不可变的,如果你拥有的变量是只读接口类型,它有可能是同一个集合众多引用中的一个,而这些引用中可能存在可写读的接口类型。

List 返回的是EmptyList,MutableList 返回的是一个 ArrayList,查看EmptyList的源码就知道了,根本就没有提供 add 方法。
internal object EmptyList : List, Serializable, RandomAccess {
private const val serialVersionUID: Long = -7390468764508069838L

override fun equals(other: Any?): Boolean = other is List<*> && other.isEmpty()
override fun hashCode(): Int = 1
override fun toString(): String = "[]"

override val size: Int get() = 0
override fun isEmpty(): Boolean = true
override fun contains(element: Nothing): Boolean = false
override fun containsAll(elements: Collection<Nothing>): Boolean = elements.isEmpty()

override fun get(index: Int): Nothing = throw IndexOutOfBoundsException("Empty list doesn't contain element at index $index.")
override fun indexOf(element: Nothing): Int = -1
override fun lastIndexOf(element: Nothing): Int = -1

override fun iterator(): Iterator<Nothing> = EmptyIterator
override fun listIterator(): ListIterator<Nothing> = EmptyIterator
override fun listIterator(index: Int): ListIterator<Nothing> {
    if (index != 0) throw IndexOutOfBoundsException("Index: $index")
    return EmptyIterator
}

override fun subList(fromIndex: Int, toIndex: Int): List<Nothing> {
    if (fromIndex == 0 && toIndex == 0) return this
    throw IndexOutOfBoundsException("fromIndex: $fromIndex, toIndex: $toIndex")
}

private fun readResolve(): Any = EmptyList

}

以前看过一篇文章,主要介绍的就是关于 MutableList 和 List 源码分析的,找不到了。