Start learning free

LESSON 103 OF 677 · ARRAYS I

ArrayList in Kotlin

Lesson

A big limitation of static arrays in Kotlin is the fact that once the array is created, it has a fixed size.

The ArrayList overcomes this limitation by having variable size and allowing for elements to be added or removed.


Creation:

We create an ArrayList by calling the mutableListOf() function, writing the type of the elements inside <> (angle brackets), like this:

mutableListOf<String>()

This code creates an empty ArrayList where each item is a String.


Casting:

A good practice is to declare the variable using its interface type MutableList and specifying there the type of the elements, like this:

val sandwich: MutableList<String> = mutableListOf()

Initialization:

You can also initialize an ArrayList at creation by passing the elements to mutableListOf() and put a comma between each entry, like this:

val sandwich = mutableListOf("peanut butter", "jelly", "bread")

We created an ArrayList named sandwich which consits of 3 items: "peanut butter", "jelly" and "bread".


Assignment
Follow the Coding Tutorial and let's create some ArrayLists!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check