What is the ArrayList.isEmpty() method in Kotlin?
The kotlin.collections package is part of Kotlin’s standard library.
It contains all collection types, such as:
MapListSet, etc.
The package provides the ArrayList class, which is a mutable list and uses a dynamic resizable array as the backing storage.
The isEmpty() method
The ArrayList class contains the isEmpty() method, which is used to check if the array list is empty or not.
If the list does not have any elements, it returns true. Otherwise, it returns false.
Syntax
fun isEmpty(): Boolean
Arguments
- This method does not take any arguments.
Return value
- It returns
trueif the list is empty, andfalseotherwise.
Things to note
-
ArrayListfollows the sequence of insertion of elements. -
It is allowed to contain duplicate elements.
The illustration below shows the function of the isEmpty() method.
Code
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 companyList = ArrayList<String>()companyList.add("Apple")companyList.add("Google")companyList.add("Microsoft")val emptyList = ArrayList<String>()println("Printing companyList elements--")println(companyList)println("Printing emptyList elements--")println(emptyList)println("Checking if companyList is empty using isEmpty() : ${companyList.isEmpty()}")println("Checking if emptyList is empty using isEmpty() : ${emptyList.isEmpty()}")}
Explanation
-
First, we create an empty array list named
companyListto store the strings. -
Next, we use the
add()method to add a few company names to theArrayListobject, such as:"Google","Apple","Microsoft", and"Netflix". -
We create another empty array list,
emptyList. -
Next, we call the
isEmpty()method on thecompanyListand it returnsfalse, as it has few elements. -
We again call the
isEmpty()method on theemptyListand it returnstrue. -
The array list elements and result of
isEmpty()method are displayed using theprint()function of thekotlin.iopackage.