5.3.2 创建可变集合MutableList

在MutableList中,除了继承List中的那些函数外,另外新增了add/addAll、remove/removeAll/removeAt、set、clear、retainAll等更新修改的操作函数。

  1. override fun add(element: E): Boolean
  2. override fun remove(element: E): Boolean
  3. override fun addAll(elements: Collection<E>): Boolean
  4. fun addAll(index: Int, elements: Collection<E>): Boolean
  5. override fun removeAll(elements: Collection<E>): Boolean
  6. override fun retainAll(elements: Collection<E>): Boolean
  7. override fun clear(): Unit
  8. operator fun set(index: Int, element: E): E
  9. fun add(index: Int, element: E): Unit
  10. fun removeAt(index: Int): E
  11. override fun listIterator(): MutableListIterator<E>
  12. override fun listIterator(index: Int): MutableListIterator<E>
  13. override fun subList(fromIndex: Int, toIndex: Int): MutableList<E>

创建一个MutableList的对象实例跟List类似,前面加上前缀mutable,代码示例如下:

  1. >>> val list = mutableListOf(1, 2, 3)
  2. >>> list
  3. [1, 2, 3]
  4. >>> list::class
  5. class java.util.ArrayList
  6. >>> val list2 = mutableListOf<Int>()
  7. >>> list2
  8. []
  9. >>> list2::class
  10. class java.util.ArrayList
  11. >>> val list3 = mutableListOf(1)
  12. >>> list3
  13. [1]
  14. >>> list3::class
  15. class java.util.ArrayList

我们可以看出,使用mutableListOf函数创建的可变集合类,实际上背后调用的是java.util.ArrayList类的相关方法。

另外,我们可以直接使用Kotlin封装的arrayListOf函数来创建一个ArrayList:

  1. >>> val list4 = arrayListOf(1, 2, 3)
  2. >>> list4::class
  3. class java.util.ArrayList

关于Kotlin中的ArrayList类型别名定义在kotlin/collections/TypeAliases.kt 文件中:

  1. @file:kotlin.jvm.JvmVersion
  2. package kotlin.collections
  3. @SinceKotlin("1.1") public typealias RandomAccess = java.util.RandomAccess
  4. @SinceKotlin("1.1") public typealias ArrayList<E> = java.util.ArrayList<E>
  5. @SinceKotlin("1.1") public typealias LinkedHashMap<K, V> = java.util.LinkedHashMap<K, V>
  6. @SinceKotlin("1.1") public typealias HashMap<K, V> = java.util.HashMap<K, V>
  7. @SinceKotlin("1.1") public typealias LinkedHashSet<E> = java.util.LinkedHashSet<E>
  8. @SinceKotlin("1.1") public typealias HashSet<E> = java.util.HashSet<E>
  9. // also @SinceKotlin("1.1")
  10. internal typealias SortedSet<E> = java.util.SortedSet<E>
  11. internal typealias TreeSet<E> = java.util.TreeSet<E>

如果我们已经有了一个不可变的List,而我们现在想把他转换成可变的List,我们可以直接调用转换函数toMutableList

  1. val list = mutableListOf(1, 2, 3)
  2. val mlist = list.toMutableList()
  3. mlist.add(5)