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 per requisites. It also provide 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.
Some of the important Methods –
add(index:Int, element: E): Boolean
It is used to add the specific element into 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 + last index of array.
Arraylist ----> Geeks Geeks Arraylist after insertion ----> Geeks For Geeks
addAll(index: Int, elements: Collection): Boolean
It is used to add all the elements of specified collection into the current list at the specified index. 1st parameter is the index value which is again optional one.
Elements in arraylist1 --> Geeks For Geeks
get(index: Int): E
It is used to return the element at specified index in the list.
10 20 30 40 50 Accessing the index 2 of arraylist: 40
set(index: Int, element: E):E
It is used to replaces the element from the specified position from current list with the specified element passed as arguments.
Geeks for Geeks: Portal Geeks for Geeks: A computer Science portal for students
indexOf(element: E): Int
It is used to return the index of first occurrence of specified element in the list and it return -1 if the specified element in not present in the list.
Geeks for Geeks The index of the element is: 0
remove(element: E): Boolean
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)
It is used to remove all the elements from the list.
10 20 30 40 50 The size of arraylist after clearing all the elements: 0
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.