Difference between MutableList and List in Kotlin

前端 未结 3 1323
情歌与酒
情歌与酒 2020-12-10 10:42
  1. What is the difference between MutableList and List in Kotlin?
  2. and what is the use of each type?
相关标签:
3条回答
  • 2020-12-10 10:52

    From docs:

    List: A generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.

    MutableList: A generic ordered collection of elements that supports adding and removing elements.

    You can modify a MutableList: change, remove, add... its elements. In a List you can only read them.

    0 讨论(0)
  • 2020-12-10 11:12
    • List

      var language: List<String> = listOf("java", "kotlin", "dart")
      

      List type is an interface which provides read-only access. you are limited to read operations like

      get, indexof, subList, contains, size etc

    with kotlin you have access to some more functions **like sort, stream,binarySearch

    • MutableList

    Consider this example:

        var mutableLanguage: MutableList<String> = mutableListOf("java", "kotlin", "dart")
    

    with mutablelist you can perform read and write operation i.e., add or remove contents of a list. beside supporting all the functions of interface type List.

    add, addAll, replace, replaceAll, set, removeAt etc

    0 讨论(0)
  • 2020-12-10 11:16

    Mutable list is used to add and alter the values . Mutable List is defined by MutableListOf () . keyword.

    Whereas Array List do the same thing but particular defined as array Array list is defined as ArrayListOf() keyword

    0 讨论(0)
提交回复
热议问题