What is the ArrayList.addAll() method in Kotlin?
The kotlin.collections package is part of Kotlin’s standard library. It contains all collection types, including Map, List, Set, etc.
The package provides the ArrayList class, which is a mutable list that uses a dynamic resizable array as the backing storage.
The addAll() method
The ArrayList class contains the addAll() method, which adds all elements of the specified input collection to the end of the array list.
Syntax
fun addAll(elements: Collection<E>): Boolean
Arguments
This method takes a collection of elements as input.
Return value
This method returns the boolean value true if the list is modified during the addAll() operation. Otherwise, it returns false.
Things to note
-
ArrayListfollows the sequence of insertion of elements. -
It is allowed to contain duplicate elements.
-
The elements are appended in the order they appear in the specified collection.
The illustration below shows the function of the addAll() method.
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 countryList = ArrayList<String>()countryList.add("India")countryList.add("US")println("Printing ArrayList elements--")println(countryList)val islandList = ArrayList<String>()islandList.add("Maldives")islandList.add("Mauritius")countryList.addAll(islandList)println("Printing ArrayList elements after calling addAll()--")println(countryList)}
Explanation
-
First, we create an empty
ArrayListto store the strings. -
Next, we add a few country names to the
ArrayListobject using theadd()method, such as:"India"and"US". -
Next, we create another array list of strings and add few island names to the new
ArrayListobject using theadd()method, such as:"Maldives"and"Mauritius". -
Next, we call the
addAll()method by passing the island names array list as the input parameter. It then adds all the elements of the island names array list to the country name array list. -
The
Arraylistelements are displayed before and after calling theaddAll()method by using theprint()function of thekotlin.iopackage. The list contains four names after calling theaddAll()method.