I am trying to use collections in Kotlin and got confused between arrayListOf and mutableListOf, which one should we use and why?
Kotlin mutableListOf() MutableList class is used to create mutable lists in which the elements can be added or removed. The method mutableListOf() returns an instance of MutableList Interface and takes the array of a particular type or mixed (depends on the type of MutableList instance) elements or it can be null also.
The major difference from usage side is that Arrays have a fixed size while (Mutable)List can adjust their size dynamically. Moreover Array is mutable whereas List is not.
ArrayList is a class that happens to implement the MutableList interface. The only difference is that arrayListOf() returns the ArrayList as an actual ArrayList. mutableListOf() returns a MutableList, so the actual ArrayList is "disguised" as just the parts that are described by the MutableList interface.
These are some important points you should know before working with Kotlin MutableList: List is read-only (immutable), you cannot add or update items in the original list. MutableList inherites List and supports read/write access, you can add, update or remove items.
Either is fine, the only difference between calling the two is expressing your intent.
ArrayList
is a concrete implementation of MutableList
, and mutableListOf
, as of Kotlin 1.1, also returns an ArrayList
.
Do you know you specifically want an ArrayList because you have made the conscious decision that this is the right choice for your application? You probably want arrayListOf
(or a direct call to the ArrayList
constructor, if that interface works better for you).
Do you just want a MutableList of some sort, and are fine with getting whatever the implementation defines as the right choice? Just use mutableListOf
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With