List and array are two popular collections supported by Kotlin. By definition, both these collections allocate sequential memory location. In this article, we will take an example to demonstrate the difference between these two types of collections.
Attribute | Array | List |
---|---|---|
Implementation | Array is implemented using Array<T> class | List<T> or MutableList<T> interfaces are used to implement a List in Kotlin |
Mutable | Array<T> is mutable, i.e., the values can be changed. | List<T> is immutable in nature. In order to create a mutable list, MutableList<T> interface needs to be used. |
Size | Array is of fixed size. It cannot increase and decrease in size. | MutableList<T> do have 'add' and 'remove' functions in order to increase or decrease the size of the MutableList. |
Performance | Use it for better performance, as array is optimized for different primitive data types such as IntArray[], DoubleArray[]. | Use it for better accessibility in the code. As the size is dynamic in nature, hence good memory management. |
Example
In the following example, we will see how we can declare an array and a List in Kotlin and how we can manipulate the values of the same.
fun main(args: Array<String>) { val a = arrayOf(1, 2, 3) // Printing all the values of array a println("The Array contains:") a.forEach{ println(it) } val names = listOf("stud1", "stud2", "stud3") // Printing all the values of list names println("\nThe List contains: ") names.forEach { println(it) } var days: MutableList<String> = mutableListOf( "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ) // Printing all the values of MutableList list println("\nGiven Mutable List contains:") days.forEach{ print(it) } println("\n\nMutable List after modification:") days.forEach{ print(it + ", ") } }
Output
It will generate the following output −
The Array contains: 1 2 3 The List contains: stud1 stud2 stud3 Given Mutable List contains: MondayTuesdayWednesdayThursdayFridaySaturdaySunday Mutable List after modification: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday,