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
Eas input and adds it to the end of the list.
Return value
- It returns
trueas the list is modified as the result of the add operation.
Things to note
-
ArrayListfollows the sequence of insertion of the elements. -
It is allowed to contain duplicate elements.
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
ArrayListto store strings. -
Next, we add a few company names to the
ArrayListobject,"Facebook","Amazon","Apple","Netflix", and"Google"using theadd()method. -
All the elements added above are displayed using the
print()function of thekotlin.iopackage.