6.1 集合类型之List 、MutableList

欢迎前往我的csdn

介绍

在Kotlin中,集合类型包含三种类型:它们分别是:List、Set、Map,这三种类型都有几个共通点:

  • 它们都是接口,并不是实际的类。
  • 它们都继承至Collection<out E>接口,而Collection< out E>又继承与Iterable< out T>接口。它们几乎上只实现了isEmpty()、size属性、get()、contains()等方法。
  • 这三种集合类型分别又存在MutableList< E>、MutableSet< E>、MutableMap<K,V>接口,这些接口中提供了改变、操作集合的方法。例如add()、clear()、remove()等函数。

so,Kotlin集合类型可分为可变和不可变集合类型。List、Set、Map为不可变集合类型,MutableList、MutableSet、MutableMap为可变集合类型。

List

创建不可变List

使用listOf函数来构建一个不可变的List,listOf这个构建函数有下面3个重载函数。

  • listOf()用于创建没有元素的空List:
/**
 * Returns an empty read-only list.  The returned list is serializable (JVM).
 * @sample samples.collections.Collections.Lists.emptyReadOnlyList
 */
@kotlin.internal.InlineOnly
public inline fun <T> listOf(): List<T> = emptyList()

  • listOf(element: T)创建只有一个元素的List:
/**
 * Returns an immutable list containing only the specified object [element].
 * The returned list is serializable.
 * @sample samples.collections.Collections.Lists.singletonReadOnlyList
 */
public fun <T> listOf(element: T): List<T> = java.util.Collections.singletonList(element)
  • listOf(vararg elements: T)创建拥有多个元素的List:
/**
 * Returns a new read-only list of given elements.  The returned list is serializable (JVM).
 * @sample samples.collections.Collections.Lists.readOnlyList
 */
public fun <T> listOf(vararg elements: T): List<T> = if (elements.size > 0) elements.asList() else emptyList()

例:

    //创建一个空List
    val numbersNull = listOf<Int>()
    
    //创建只有一个元素的List
    val numbersOne = listOf<Int>(1)

    //创建多个元素的List
    val numbersMuch = listOf<Int>(1, 2, 4, 9, 3, 5, 6, 1, 0, -1)
    
    println(numbersNull)
    println(numbersOne)
    println(numbersMuch)

结果:

[]
[1]
[1, 2, 4, 9, 3, 5, 6, 1, 0, -1]

List的方法

get: 根据索引获取元素,与[]等效:
例:

    val num = listOf("alfred", 29, "男", "180cm", "70kg")
    println(num.get(0))
    println(num[0])

结果:

alfred
alfred

indexOf: 返回集合元素在List中的索引。
例:

    val num = listOf("alfred", 29, "男", "180cm", "70kg")
    println(num.indexOf(29))

结果:1
lastIndexOf: 返回集合元素在List中最后一次的出现位置。
例:

    val num = listOf(1, "alfred", 29, "男", "180cm", 1, "70kg")
    println(num.lastIndexOf(1))

结果:5
subList: 返回List集合的子集合。
先来看个源码:

 // View
    /**
     * Returns a view of the portion of this list between the specified [fromIndex] (inclusive) and [toIndex] (exclusive).
     * The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
     *
     * Structural changes in the base list make the behavior of the view undefined.
     */
    public fun subList(fromIndex: Int, toIndex: Int): List<E>

注意:此处是开区间[fromIndex,toIndex)
例:

    val num = listOf("alfred", 29, "男", "180cm", "70kg")
    println(num.subList(1, 5))

结果:[29, 男, 180cm, 70kg]

MutableList

创建MutableList

创建MutableList的方法有两种

  • mutableListOf():创建空的可变List
/**
 * Returns an empty new [MutableList].
 * @sample samples.collections.Collections.Lists.emptyMutableList
 */
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> mutableListOf(): MutableList<T> = ArrayList()
  • mutableListOf(vararg elements: T): 创建拥有多个元素的可变List
/**
 * Returns a new [MutableList] with the given elements.
 * @sample samples.collections.Collections.Lists.mutableList
 */
public fun <T> mutableListOf(vararg elements: T): MutableList<T> =
    if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))

例:

    //和粗昂吉安空的可变list
    val numNull = mutableListOf<Int>()
    //创建多个元素的可变list
    val numMutable = mutableListOf("Alfred", 29, "男", "180cm", "70kg")

    println(numNull)
    println(numMutable)

结果:

[]
[Alfred, 29, 男, 180cm, 70kg]

MutableList常用方法:

可变的List除了支持可变的Set所支持的方法外,还增加了根据索引执行插入、删除、替换等方法,下面一一讲解:

add()

往末尾增加新的元素:

    val numMutable = mutableListOf("Alfred", 29, "男", "180cm", "70kg")

    numMutable.add("黄种人")
    println(numMutable)

结果:

[Alfred, 29, 男, 180cm, 70kg, 黄种人]

往指定位置添加元素
源码:

   /**
     * Inserts an element into the list at the specified [index].
     */
    public fun add(index: Int, element: E): Unit

例:

    val numMutable = mutableListOf("Alfred", 29, "男", "180cm", "70kg")

    numMutable.add(1,"黄种人")
    println(numMutable)

结果:

[Alfred, 黄种人, 29, 男, 180cm, 70kg]
addAll

在末尾添加另外一个集合的所有元素:
源码:

    /**
     * Adds all of the elements of the specified collection to the end of this list.
     *
     * The elements are appended in the order they appear in the [elements] collection.
     *
     * @return `true` if the list was changed as the result of the operation.
     */
    override fun addAll(elements: Collection<E>): Boolean

例:

    val numMutable = mutableListOf("Alfred", 29, "男", "180cm", "70kg")
    val num = listOf("1", 2, 3, 4, 5, 6, "***")

    numMutable.addAll(num)
    println(numMutable)

结果:

[Alfred, 29, 男, 180cm, 70kg, 1, 2, 3, 4, 5, 6, ***]

向指定位置添加整个集合的元素:
源码:


    /**
     * Inserts all of the elements of the specified collection [elements] into this list at the specified [index].
     *
     * @return `true` if the list was changed as the result of the operation.
     */
    public fun addAll(index: Int, elements: Collection<E>): Boolean

根据源码分析,向指定位置添加元素,成功会返回true
例:

    val numMutable = mutableListOf("Alfred", 29, "男", "180cm", "70kg")
    val num = listOf("1", 2, 3, 4, 5, 6, "***")
    
    val  result = numMutable.addAll(1, num)
    println("add $result\n$numMutable")

结果:

add true
[Alfred, 1, 2, 3, 4, 5, 6, ***, 29, 男, 180cm, 70kg]
移除元素

remove:移除某个元素

    val numMutable = mutableListOf("Alfred", 29, "男", "180cm", "70kg")
    numMutable.remove(29)
    println(numMutable)

结果:[Alfred, 男, 180cm, 70kg]
removeAt 移除指定位置的元素

    val numMutable = mutableListOf("Alfred", 29, "男", "180cm", "70kg")
    numMutable.removeAt(0)
    println(numMutable)

结果:[29, 男, 180cm, 70kg]
removeAll(elements: Collection<E>):删除集合
例子:

    val numMutable = mutableListOf("Alfred", 29, "男", "180cm", "70kg", 29)
    //清空自身
    numMutable.removeAll(numMutable)
    println(numMutable)
    
    val numMutable1 = mutableListOf("Alfred", 29, "男", "180cm", "70kg", 29)
    val numMutable2 = mutableListOf(1, 2, 3, 4, 5)
    numMutable1.addAll(numMutable2)
    println(numMutable1)
    //将集合numMutable1中的numMutable2全部清除
    numMutable1.removeAll(numMutable2)
    println(numMutable1)

结果:

[]
[Alfred, 29, 男, 180cm, 70kg, 29, 1, 2, 3, 4, 5]
[Alfred, 29, 男, 180cm, 70kg, 29]

clear:清除所有元素 与removeAll()类似

    val numMutableClear = mutableListOf("Alfred", 29, "男", "180cm", "70kg", 29)
    numMutableClear.clear()
    println(numMutableClear)

结果[]

set

替换指定位置元素:

    val numMutable = mutableListOf("Alfred", 29, "男", "180cm", "70kg")
    numMutable.set(0,"你好")
    println(numMutable)

结果:[你好, 29, 男, 180cm, 70kg]
也可以用下标方式改写:

    val numMutable = mutableListOf("Alfred", 29, "男", "180cm", "70kg")
    numMutable[0] = "你好"
    println(numMutable)

结果:[你好, 29, 男, 180cm, 70kg]

drop

drop与remove不同点在于,drop系列方法不会对MutableList本身造成影响,drop会返回删除后的list,在数组已经介绍过,此处不再讲解。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容