📅  最后修改于: 2023-12-03 15:13:29.888000             🧑  作者: Mango
ArrayList in Kotlin is a type of list which is mutable in nature. It means we can add, remove, and change the elements of the list. It is similar to an array but with dynamic size. ArrayList is one of the commonly used collections in Kotlin.
We can create ArrayList in Kotlin using the ArrayList()
constructor or arrayListOf()
function.
// Using ArrayList() constructor
val list1: ArrayList<String> = ArrayList()
// Using arrayListOf() function
val list2: ArrayList<Int> = arrayListOf(1, 2, 3, 4)
Both the above statements create an ArrayList, but with different initializations. Here list1
is empty, whereas list2
contains four elements.
We can add elements to the ArrayList using the add()
function or addAll()
function.
// Adding single element
list1.add("apple")
// Adding multiple elements
list1.addAll(listOf("banana", "cherry"))
In the above code snippet, we are adding elements to list1
. We can add a single element or multiple elements at once using the addAll()
function.
We can remove elements from the ArrayList using the remove()
function or removeAt()
function.
// Removing a single element
list1.remove("apple")
// Removing element at index
list1.removeAt(1)
In the above code snippet, we are removing elements from list1
. We can remove a single element or element at a particular index using the remove()
and removeAt()
functions, respectively.
We can access elements of the ArrayList using the index of the element. Indexing in ArrayList is zero-based.
// Accessing single element
val element: String = list1[0]
// Accessing a range of elements
val subList: List<Int> = list2.subList(1, 3)
In the above code snippet, we are accessing elements of list1
and list2
. We can access a single element using the index of the element. We can also access a range of elements using the subList()
function.
ArrayList in Kotlin is a versatile collection that makes it easy to manage and manipulate elements of a list. It offers various functions for adding, removing, and accessing elements. With the help of these functions, we can perform various operations on the list easily.