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

  • 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.

Getting the element at a specified index in the list
fun main(args : Array<String>) {
//create the list of string
val subjectsList = ArrayList<String>()
// add element in list
subjectsList.add("Maths")
subjectsList.add("English")
subjectsList.add("History")
subjectsList.add("Geography")
println("Printing ArrayList elements --")
// print the list
println(subjectsList)
// get element of list and print it
var element = subjectsList.get(1)
println("Element at index 1 is ${element}")
}

Explanation

  • 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.

Free Resources