Skip to main content

How to clear an ArrayList in Kotlin

How to clear an ArrayList in Kotlin.

How to Clear an ArrayList in Kotlin

An ArrayList is a dynamic array that can grow or shrink in size. Sometimes, we may need to remove all elements from an ArrayList in Kotlin. In this tutorial, we will learn different ways to clear an ArrayList using Kotlin.

Method 1: Using the clear() function

The most straightforward way to clear an ArrayList in Kotlin is by using the clear() function. This function removes all elements from the ArrayList, leaving it empty. Here's an example:

val fruits = ArrayList<String>()
fruits.add("Apple")
fruits.add("Banana")
fruits.add("Orange")

fruits.clear()

After calling the clear() function, the fruits ArrayList will be empty.

Method 2: Using removeAll() function with an empty collection

Another way to clear an ArrayList in Kotlin is by using the removeAll() function with an empty collection. This function removes all elements from the ArrayList that exist in the specified collection. When an empty collection is passed, it removes all elements, effectively clearing the ArrayList. Here's an example:

val fruits = ArrayList<String>()
fruits.add("Apple")
fruits.add("Banana")
fruits.add("Orange")

fruits.removeAll(emptyList())

After calling the removeAll() function with an empty list, the fruits ArrayList will be empty.

Method 3: Creating a new ArrayList

If you don't need to keep the reference to the original ArrayList, you can simply create a new ArrayList to clear the existing one. This method is useful when you want a fresh ArrayList with no elements. Here's an example:

val fruits = ArrayList<String>()
fruits.add("Apple")
fruits.add("Banana")
fruits.add("Orange")

val emptyFruits = ArrayList<String>()
fruits.clear()
fruits.addAll(emptyFruits)

In this example, we create a new emptyFruits ArrayList and then clear the original fruits ArrayList. Finally, we add all the elements from emptyFruits back to the fruits ArrayList, effectively clearing it.

Method 4: Reassigning an empty ArrayList

Similar to the previous method, you can also clear an ArrayList by reassigning it to a new empty ArrayList. This method is useful when you need to keep the original reference to the ArrayList. Here's an example:

val fruits = ArrayList<String>()
fruits.add("Apple")
fruits.add("Banana")
fruits.add("Orange")

fruits = ArrayList<String>()

In this example, we first create an fruits ArrayList and add some elements. Then, we reassign fruits to a new empty ArrayList, effectively clearing it.

These are the different ways to clear an ArrayList in Kotlin. Choose the method that best suits your needs and clear your ArrayList with ease.