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.
get()
methodThe ArrayList
class contains the get()
method, which returns the element at a specified index in the array list.
fun get(index: Int): E
This method takes an integer index as input.
The get()
method returns the element present at the input index in the list.
ArrayList
follows the sequence of insertion of elements.
ArrayList
is 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}")}
Line 2: We create an empty array list named subjectsList
to 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 as 1
. The method returns "English"
, the element present at index 1
in the list.
We use the println()
function of the kotlin.io
package to display the ArrayList
elements and result of the get()
method.