Kotlin arrayListOf()
In Kotlin, arrayListOf()
is a function that creates a new ArrayList containing the elements specified within the parentheses. The ArrayList class is a generic class that provides a resizable array implementation of the List interface.
Syntax
The syntax for using arrayListOf()
in Kotlin is:
val list = arrayListOf(element1, element2, element3, ...)
The val
keyword declares an immutable variable that cannot be reassigned. list
is the name of the variable that will store the ArrayList. element1
, element2
, and element3
are the elements that will be added to the ArrayList. You can add as many elements as needed.
Example
Let's create an ArrayList in Kotlin using the arrayListOf()
function. We will add three elements to the ArrayList: "apple", "banana", and "orange".
val fruits = arrayListOf("apple", "banana", "orange")
println(fruits)
Output
When the above code is executed, it produces the following output:
[apple, banana, orange]
Explanation
The arrayListOf()
function creates a new ArrayList and initializes it with the elements specified in the parentheses. In our example, we created an ArrayList called fruits
that contains three elements: "apple", "banana", and "orange". The println()
function is used to print the elements of the fruits
ArrayList.
Use
The arrayListOf()
function is commonly used to create an ArrayList of a specific type in Kotlin. You can add any number of elements to an ArrayList created using this function, and it will automatically resize as needed.
Important Points
- The ArrayList class in Kotlin is a generic class, which means you can create an ArrayList of any type.
- The
arrayListOf()
function creates an ArrayList with the specified elements and returns a reference to the ArrayList. - You can add, remove, and modify elements in an ArrayList using built-in methods such as
add()
andremoveAt()
. - ArrayLists provide more efficient element access than regular arrays in Kotlin.
Summary
arrayListOf()
is a function in Kotlin that creates an ArrayList containing the elements specified within the parentheses. The ArrayList class is a generic class that provides a resizable array implementation of the List interface. With arrayListOf()
, you can easily create an ArrayList of any type and add or remove elements as needed.