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.
addAll()
methodThe ArrayList
class contains the addAll()
method, which adds all elements of the specified input collection to the end of the array list.
fun addAll(elements: Collection<E>): Boolean
This method takes a collection of elements as input.
This method returns the boolean value true
if the list is modified during the addAll()
operation. Otherwise, it returns false
.
ArrayList
follows 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.
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)}
First, we create an empty ArrayList
to store the strings.
Next, we add a few country names to the ArrayList
object using the add()
method, such as: "India"
and "US"
.
Next, we create another array list of strings and add few island names to the new ArrayList
object using the add()
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 Arraylist
elements are displayed before and after calling the addAll()
method by using the print()
function of the kotlin.io
package. The list contains four names after calling the addAll()
method.