What is the ArrayList.remove() method in Kotlin?

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.

The remove() method

The ArrayList class contains the remove() method which removes the single instance of the specified element from the array list.

Syntax

fun remove(element: E): Boolean

Parameters

  • This method takes the element to remove as the input.

Return value

  • It returns true if the element is successfully removed from the array list and false if the input element is not present in the collection.

Things to note

  • ArrayList follows the sequence of insertion of elements.

  • It is allowed to contain duplicate elements.

The illustration below shows the function of the remove() method.

Removing an element from an array list using the remove() method

Code

Run the code below to see how the remove() method works.

fun main(args : Array<String>) {
val monthList = ArrayList<String>()
monthList.add("January")
monthList.add("February")
monthList.add("December")
monthList.add("March")
monthList.add("April")
println("Printing ArrayList elements --")
println(monthList)
monthList.remove("December")
println("Printing ArrayList elements after calling remove() --")
println(monthList)
}

Explanation

  • Line 2: We create an empty array list named monthList to store the strings.

  • Line 4 to 8: We add a few month names to the ArrayList object using the add() method, such as: "January", "February", "December", "March", and "April".

  • Line 12: We call the remove() method and pass the input string as "December". It removes the element "December" present in the list at index 2 and returns true.

The Arraylist elements and result of the remove() method are displayed using the println() function of the kotlin package.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources