What is the ArrayList.get() method in Kotlin?
Overview
The kotlin.collections package is part of Kotlin’s standard library and contains all collection types, such as Map, List, Set, etc.
The package provides the ArrayList class, which is a mutable list and uses a dynamic, resizable array as the backing storage.
The get() method
The ArrayList class contains the get() method, which returns the element at a specified index in the array list.
Syntax
fun get(index: Int): E
Parameters
This method takes an integer index as input.
Return value
The get() method returns the element present at the input index in the list.
Things to note
-
ArrayListfollows the sequence of insertion of elements. -
ArrayListis allowed to contain duplicate elements.
The illustration below shows the function of the get() method.
fun main(args : Array<String>) {//create the list of stringval subjectsList = ArrayList<String>()// add element in listsubjectsList.add("Maths")subjectsList.add("English")subjectsList.add("History")subjectsList.add("Geography")println("Printing ArrayList elements --")// print the listprintln(subjectsList)// get element of list and print itvar element = subjectsList.get(1)println("Element at index 1 is ${element}")}
Explanation
-
Line 2: We create an empty array list named
subjectsListto store the strings. -
Lines 4 to 7: We use the
add()method to add a few subject names to the ArrayList object, such as"Maths","English","History", and"Geography". -
Line 11: We call the
get()method and pass the input index as1. The method returns"English", the element present at index1in the list.
We use the println() function of the kotlin.io package to display the ArrayList elements and result of the get() method.