Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between arrayListOf and mutableListOf , which one is better? [duplicate]

I am trying to use collections in Kotlin and got confused between arrayListOf and mutableListOf, which one should we use and why?

like image 292
shekar Avatar asked Apr 03 '17 10:04

shekar


People also ask

What is mutableListOf?

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.

What is the difference between Arrayof and listof in Kotlin?

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.

What is difference between mutable list and ArrayList Kotlin?

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.

What is the difference between list and MutableList in Kotlin?

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.


1 Answers

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.

like image 97
pdpi Avatar answered Sep 23 '22 16:09

pdpi