Kotlin: Array vs List - Similarities and Differences
// Initializing array and list val array = arrayOf(1, 2, 3) //pure array val list = listOf("apple", "ball", "cow") //pure list val mixedArray = arrayOf(true, 2.5, 1, 1.3f, 12000L, 'a') // mixed Array val mixedList = listOf(false, 3.5, 2, 1.4f, 13000L, 'b') // mixed List
Arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Arrays can be concatenated to give a new Array
val array1 = arrayOf(1, 2, 3, 4, 5, 6) val array2 = arrayOf(7, 8, 9, 10, 11, 12) val newArray = array1 + array2 for(element in newArray) { println("$element - ") } // 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12
Lists
A list is an interface. It is a generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.Similarities
- Both have finite set of element. You cannot add extra elements after initialization. They have fixed size and cannot be expand or shrank
array.add(1) // cannot be expanded or shrank list.add("dog") // cannot be expanded or shrank
- Both are containers used to store multiple elements which are commonly referred to as Collections
val array = arrayOf(1, 2, 3) val list = listOf("apple", "ball", "cow")
Differences
- Arrays are mutable (it can be changed through any reference to it). It's content can be reassigned. Lists are immutable
val array = arrayOf(1, 2, 3) array[2] = 4 // OK for (element in array){ println("$element, ") // 1, 2, 4 } val list = listOf("apple", "ball", "cow") list[2] = "cat" //will not compile, lists are immutable // println(list) = {apple, ball, cow}
- 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 is mapped to Java's Integer[]). Lists in general do not have implementations optimized for primitives.
val optimisedIntegerArray = intArrayOf(1, 2, 3, 4, 5, 6) // optimised for Integer Array val optimisedDoubleArray = doubleArrayOf(1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8) // Optimised for Double Array val optimisedCharacterArray = charArrayOf('a', 'b', 'c', 'd') // Optimised for Character Array //List does not have intListOf, charListOf as such it is not optimised for primitive arrays
- Array<TYPE> is a class with known implementation: it's a sequential fixed-size memory region storing the items (and on JVM it is represented by Java array). List<T> and MutableList<T> are interfaces which have different implementations: ArrayList<T>, LinkedList<T> etc
- As to the usage, good practice is to prefer using lists over arrays everywhere except for performance critical parts of your code, the arguments are the same to those for Java.
Comments
Post a Comment