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.
add()
methodThe ArrayList
class contains the add(E)
method which adds the specified input element to the end of the list.
fun add(element: E): Boolean
E
as input and adds it to the end of the list.true
as the list is modified as the result of the add operation.ArrayList
follows the sequence of insertion of the elements.
It is allowed to contain duplicate elements.
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)}
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.