The kotlin.collections
package is part of Kotlin’s standard library, and it contains all collection types, such as Map
, List
, Set
, etc.
The package provides the ArrayList
class which is a mutable list and uses a dynamic resizable array as the backing storage.
clear()
methodThe ArrayList
class contains the clear()
method which removes all the elements from the list.
fun clear()
ArrayList
follows the sequence of insertion of elements.
It is allowed to contain duplicate elements.
The illustration below shows the function of the clear()
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 fruitList = ArrayList<String>()fruitList.add("Apple")fruitList.add("Mango")fruitList.add("Grapes")fruitList.add("Orange")println("Printing ArrayList elements--")println(fruitList)fruitList.clear();println("Printing ArrayList elements after calling clear()--")println(fruitList)}
First, we create an empty ArrayList
to store the strings.
Next, we add a few fruits to the ArrayList
object, using the add()
method such as: "Apple"
, "Mango"
, "Grapes"
, and "Orange"
.
Next, we call the clear()
method and it removes all the elements from the Arraylist
.
The Arraylist
elements are displayed before and after calling the clear()
method by using the print()
function of the kotlin.io
package. The list is emptied after calling the clear()
method.