Skip to main content

How to get the size of an ArrayList in Kotlin

How to get the size of an ArrayList in Kotlin.

Here's a detailed step-by-step tutorial on how to get the size of an ArrayList in Kotlin:

Step 1: Create an ArrayList

To get the size of an ArrayList, we first need to create an ArrayList in Kotlin. You can create an ArrayList of any type by using the ArrayList class and specifying the desired type in angle brackets. For example, to create an ArrayList of integers, you can use the following code:

val numbers = ArrayList<Int>()

Step 2: Add elements to the ArrayList

Next, you can add elements to the ArrayList using the add() method. This method takes the element you want to add as an argument. Here's an example of adding elements to the numbers ArrayList:

numbers.add(1)
numbers.add(2)
numbers.add(3)

Step 3: Get the size of the ArrayList

To get the size of the ArrayList, you can use the size property. The size property returns the number of elements in the ArrayList. Here's an example of getting the size of the numbers ArrayList:

val size = numbers.size
println("Size of the ArrayList: $size")

In this example, the value of the size variable will be the number of elements in the numbers ArrayList. The value will be printed to the console using println().

Step 4: Access the size of the ArrayList

You can also directly access the size of the ArrayList without storing it in a separate variable. Here's an example:

println("Size of the ArrayList: ${numbers.size}")

In this example, the size of the numbers ArrayList will be printed directly to the console.

Step 5: Handling an empty ArrayList

If the ArrayList is empty, i.e., it doesn't contain any elements, the size property will return 0. You can handle this case by checking if the size is 0. For example:

if (numbers.isEmpty()) {
println("The ArrayList is empty.")
} else {
println("Size of the ArrayList: ${numbers.size}")
}

In this example, if the numbers ArrayList is empty, the message "The ArrayList is empty." will be printed. Otherwise, the size of the ArrayList will be printed.

That's it! You've learned how to get the size of an ArrayList in Kotlin. You can use the size property to retrieve the number of elements in an ArrayList and handle the case when the ArrayList is empty.