![]() ![]() If you want to get the index of an item in a Mutable List you can use the function indexOf(). Hawkins Get the index of an item in a Mutable List We will be using a for loop here to iterate over the Mutable List. It means you can loop through the items of the Mutable List and use the item in each iteration of the loop. Output Iterate over a Mutable ListĪs we all know Mutable Lists in Kotlin are iterable items. print the updated mutable list - students Val students = mutableListOf("John", "Kerry", "Carl", "Hawkins") It takes the index of the item as a parameter and removes that element using the index. We can use the Mutable List function removeAt() to remove an item from the list. We can also remove items from a Mutable list using the index of the item. Output Remove an item from the Mutable List The mutable list has a function add() that takes the item as a parameter and adds that item to the list.Ĭode Example val numbers = mutableListOf(20, 25, 30, 35, 40, 45) If you are using Mutable List in Kotlin, you can easily add new items to it. access items using square brackets and index val cars = mutableListOf("TATA", "Nexa", "Tesla", "Volvo") ![]() You can access them using index and square brackets or you can also use the get() function for that and pass the item index. ![]() The items of a mutable list can be accessed using its index. I prefer to add my own extension to be sure of the result and create a much more clear code (just like we have for arrays): fun List.Interface MutableList : List, MutableCollectionĬreate a mutable list - integer type items val mList = mutableListOf(10, 20, 30, 40, 50, 60)Ĭreate a mutable list - string type items val names = mutableListOf("Tony", "John", "Martin", "Krusten") For instance, adding the following line at the beginning of the extension: if (this is List) return this is a legitimate performance improvement (if it indeed improves the performance).Īlso, because of its name, the resulting code isn't very clear. Nothing guarantees you that it's going to be a new list. Unfortunately, as its signature and documentation suggest, it's meant to ensure that an Iterable is a List (just like toString and many other to methods). You can use the provided extension Iterable.toMutableList() which will provide you with a new list. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |