![]() |
VOOZH | about |
The ArrayList class is used to create a dynamic array in Kotlin. Dynamic array states that we can increase or decrease the size of an array as a prerequisite. It also provides read and write functionalities. ArrayList may contain duplicates and is non-synchronized in nature. We use ArrayList to access the index of the specified element, convert an Arraylist into string or another array and many more functionalities.
1) ArrayList<E>(): - Creates an empty ArrayList
2) ArrayList(capacity: Int): - Creates an ArrayList of specified size.
3) ArrayList(elements: Collection<E>): - Create an ArrayList filled by collection elements.
It is used to add a specific element to the ArrayList. The 2nd parameter contains the element to be added, which is the mandatory one, and the 1st one is the index to which we want to add the element; it is optional, and by default, the value of it is 1 + the last index of an array.
Output:
Array list ---->
Geeks
Geeks
Arraylist after insertion ---->
Geeks
For
Geeks
It is used to add all the elements of the specified collection into the current list at the specified index. 1st parameter is the index value, which is again an optional one.
Output:
Elements in arraylist1 -->
Geeks
For
Geeks
It is used to return the element at the specified index in the list.
Output:
10 20 30 40 50
Accessing the index 2 of arraylist: 30
It is used to replaces the element from the specified position from current list with the specified element passed as arguments.
Output:
Geeks for Geeks: Portal
Geeks for Geeks: A computer Science portal for students
It is used to return the index of first occurrence of specified element in the list and it return -1 if the specified element is not present in the list.
Output:
Geeks for Geeks
The index of the element is: 0
It is used to remove the first occurrence of the specific element from current collection, if it is available. Similarly for removing element at index i we use removeAt(index).
Output:
Geeks GeeksIt is used to remove all the elements from the list.
Output:
10 20 30 40 50
The size of arraylist after clearing all the elements: 0
In Kotlin, an ArrayList is a resizable list implementation backed by an array, similar to the ArrayList in Java. It allows dynamic resizing of the list and provides various methods for adding, removing, and manipulating elements in the list.
Output:
Initial list: [1, 2, 3]
After adding elements: [1, 5, 2, 3, 4]
After removing elements: [5, 3, 4]
After updating elements: [6, 3, 4]
First element: 6
Last element: 4
6
3
4
Here are some advantages and disadvantages of using an ArrayList in Kotlin:
Overall, ArrayList is a powerful and flexible collection type that is useful in many situations, but it may not always be the best choice depending on the specific requirements of your program.