Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Moosphan opened this issue Jul 4, 2019 · 7 comments
Open

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

Moosphan opened this issue Jul 4, 2019 · 7 comments
Labels

Comments

@Moosphan
Copy link
Owner

Moosphan commented Jul 4, 2019

No description provided.

@Moosphan Moosphan added the Kotlin label Jul 4, 2019
@ADrunkenLiBai
Copy link

Ground floor

@DaveBoy
Copy link

DaveBoy commented Jul 4, 2019

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

@gabyallen
Copy link

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

@ADrunkenLiBai
Copy link

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

@18361237136
Copy link

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

@dashu52
Copy link

dashu52 commented Aug 10, 2019

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

@Monkey-D-Vincent
Copy link

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 源码分析的,找不到了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

7 participants