What is the ArrayList.add() method in Kotlin?

The kotlin.collections package contains all collection types, such as Map, List, Set, etc., and is part of Kotlin’s standard library.

The package provides the ArrayList class which is a mutable list and uses a dynamic resizable array as the backing storage.

The add() method

The ArrayList class contains the add(E) method which adds the specified input element to the end of the list.

Syntax

fun add(element: E): Boolean

Arguments

  • This method takes an element of type E as input and adds it to the end of the list.

Return value

  • It returns true as the list is modified as the result of the add operation.

Things to note

  • ArrayList follows the sequence of insertion of the elements.

  • It is allowed to contain duplicate elements.

Using add() method to add elements to the ArrayList

Code

The ArrayList class is present in the kotlin.collection package and is imported by default in every Kotlin program.

fun main(args : Array<String>) {
val companyList = ArrayList<String>()
companyList.add("Facebook")
companyList.add("Amazon")
companyList.add("Apple")
companyList.add("Netflix")
companyList.add("Google")
println("Printing ArrayList elements--")
print(companyList)
}

Explanation

  • First, we create an empty ArrayList to store strings.

  • Next, we add a few company names to the ArrayList object, "Facebook", "Amazon", "Apple", "Netflix", and "Google" using the add() method.

  • All the elements added above are displayed using the print() function of the kotlin.io package.

Free Resources