Reputation: 1802
How to add an item to an ArrayList
in Kotlin?
Upvotes: 125
Views: 219180
Reputation: 168
This is a code sample of how to add an item in a String
ArrayList
in Kotlin.
val arrayList: ArrayList<String> = ArrayList()
arrayList.add("January")
Upvotes: 3
Reputation: 1251
What I was doing was storing a list of strings in the viewmodel and accessing it in the fragment.
I created a dialog fragment and was editing the string in the dialog and returning the string value to the main fragment using navigation components.
When entering the dialog fragment the viewmodel was being cleared and the list with it. so when I wud pass the list to the adapter it would not really show anything and have a reference error.
Also, when passing list to adapter add ,toList()
`adapter.subMItList(viewModel.lableList.toList())`
Upvotes: 0
Reputation: 473
You can add a new item to an array using +=
, for example:
private var songs: Array<String> = arrayOf()
fun add(input: String) {
songs += input
}
Upvotes: 11
Reputation: 12167
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.
Upvotes: 95
Reputation: 8674
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.
Upvotes: 158
Reputation: 1709
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.
Upvotes: 36