How to add an item to an ArrayList in Kotlin?

后端 未结 4 1396
半阙折子戏
半阙折子戏 2021-01-31 01:13

How to add an item to an ArrayList in Kotlin?

相关标签:
4条回答
  • 2021-01-31 01:21

    You can add element to arrayList using add() method in Kotlin. For example,

    arrayList.add(10)
    

    Above code will add element 10 to arrayList.

    However, if you are using Array or List, then you can not add element. This is because Array and List are Immutable. If you want to add element, you will have to use MutableList.

    Several workarounds:

    1. Using System.arraycopy() method: You can achieve same target by creating new array and copying all the data from existing array into new one along with new values. This way you will have new array with all desired values(Existing and New values)
    2. Using MutableList:: Convert array into mutableList using toMutableList() method. Then, add element into it.
    3. Using Array.copyof(): Somewhat similar as System.arraycopy() method.
    0 讨论(0)
  • 2021-01-31 01:28

    If you want to specifically use java ArrayList then you can do something like this:

    fun initList(){
        val list: ArrayList<String> = ArrayList()
        list.add("text")
        println(list)
    }
    

    Otherwise @guenhter answer is the one you are looking for.

    0 讨论(0)
  • 2021-01-31 01:44

    For people just migrating from java, In Kotlin List is by default immutable and mutable version of Lists is called MutableList.

    Hence if you have something like :

    val list: List<String> = ArrayList()
    

    In this case you will not get an add() method as list is immutable. Hence you will have to declare a MutableList as shown below :

    val list: MutableList<String> = ArrayList()
    

    Now you will see an add() method and you can add elements to any list.

    0 讨论(0)
  • 2021-01-31 01:47

    If you have a MUTABLE collection:

    val list = mutableListOf(1, 2, 3)
    list += 4
    

    If you have an IMMUTABLE collection:

    var list = listOf(1, 2, 3)
    list += 4
    

    note that I use val for the mutable list to emphasize that the object is always the same, but its content changes.

    In case of the immutable list, you have to make it var. A new object is created by the += operator with the additional value.

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