val array = arrayListOf(1)
array.add(3)
val list = mutableListOf(1)
list.add(3)
Seems like this both data structures has the same methods and approaches. I don't understand then why do we need MutableList.
In which cases I need to use ArrayList and MutableList?
What data structure is MutableList implements? It's array or something different?
I already read official documentation. I learned a lot about arrays. But I don't understand difference between ArrayList and MutableList.
The difference is that MutableList
is just an interface (similar to List
, but with additional methods to modify its data), and ArrayList
is one of its implementations.
As for the code from the question, both mutableListOf(1)
and arrayListOf(1)
create an ArrayList
under the hood, but they have different return types, in accordance with their names – the former returns a mutable list as an interface, while the latter provides a specific implementation, i.e., ArrayList
.
Regarding val array = arrayListOf(1)
, it's not actually an array; it's still a list. The structure is called ArrayList
simply because it uses an array in its internal implementation. If you want to create an array, you can use arrayOf()
for everything but primitive types, and intArrayOf()
, floatArrayOf()
, etc. for the primitives.