What is the difference between List
and Array
types?
It seems can make same operations with them (loops, filter expression, etc..), is there any difference in behavior or usage?
val names1 = listOf("Joe","Ben","Thomas")
val names2 = arrayOf("Joe","Ben","Thomas")
for (name in names1)
println(name)
for (name in names2)
println(name)
Arrays and lists (represented by List<T>
and its subtype MutableList<T>
) have many differences, here are the most significant ones:
Array
Array
Arrays have fixed size and cannot expand or shrink retaining identity (you need to copy an array to resize it). As to the lists, MutableList
Array
Arrays are optimized for primitives: there are separate IntArray, DoubleArray, CharArray etc. which are mapped to Java primitive arrays (int[], double[], char[]), not boxed ones (Array
List
Certain array types are used in annotations (primitive arrays, Array
As to the usage, good practice is to prefer using lists over arrays everywhere except for performance critical parts of your code, the reasoning is the same to that for Java.
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.
Furthermore kotlin.collections.List
is an interface implemented among others by java.util.ArrayList
. It's also extended by kotlin.collections.MutableList
to be used when a collection that allows for item modification is needed.
On the jvm level, Array
is represented by arrays. List
on the other hand is represented by java.util.List
since there are no immutable collections equivalents available in Java.
In additional to the above, identity comparison is also different:
val l1 = listOf("a")
val l2 = listOf("a")
var x = (l1 == l2) // => true
val a1 = arrayOf("a")
val a2 = arrayOf("a")
var y = (a1 == a2) // => false
Success story sharing
Array
? Only it's elements - the same in theList
. The size ofList
is also fixed.val intArray = arrayOf(1,2,3); intArray[0] = 2
while this will notval intList = listOf(1,2,3); intList[0] = 2
. TheList
indeed has a fixed size butMutableList
which extends it doesn't hence it is possible that aval a:List<Int>
will report differentsize
on subsequent calls.List
orArrayList
?List
(probably 99% of the cases 🙂). If you do care about implementation useArrayList
orLinkedList
or any other concrete implementation.