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 ArrayList
class contains the remove()
method which removes the single instance of the specified element from the array list.
fun remove(element: E): Boolean
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.
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)}
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.