How are Kotlin Array's toList and asList different?

后端 未结 2 1837
青春惊慌失措
青春惊慌失措 2020-12-28 15:40

The Kotlin Array class offers asList(), toList(), and toMutableList() methods. The first two methods both return a

2条回答
  •  一向
    一向 (楼主)
    2020-12-28 16:21

    TL;DR

    The list created with asList keeps a reference to the original Array.
    The list created with toList/toMutableList is backed by a copy of the original Array.

    Explanation

    asList

    The asList function creates a list that reuses the same Array instance, which implies that changes to the original array also have impact on the List:

    val arr = arrayOf(1, 2, 3)
    val l1 = arr.asList()
    
    arr[0] = 4
    println(l1) // [4, 2, 3]
    

    toList

    This isn't the case for toList/toMutableList since the array is copied:

    val arr = arrayOf(1, 2, 3)
    val l2 = arr.toList()
    
    arr[0] = 4
    println(l2) // [1, 2, 3]
    

    The Kotlin source code can be found here.

提交回复
热议问题