0
0
KotlinComparisonBeginner · 3 min read

List vs ArrayList in Kotlin: Key Differences and Usage

In Kotlin, List is a read-only interface representing an ordered collection of elements, while ArrayList is a mutable implementation of the MutableList interface backed by a resizable array. Use List when you want an immutable collection and ArrayList when you need to modify the list dynamically.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of List and ArrayList in Kotlin.

FeatureListArrayList
MutabilityRead-only (immutable)Mutable (modifiable)
TypeInterfaceClass (implementation)
Backing StructureDepends on implementationResizable array
Modification MethodsNot availableAvailable (add, remove, etc.)
UsageFor fixed or read-only dataFor dynamic, changeable data
PerformanceDepends on implementationFast random access and modification
⚖️

Key Differences

List in Kotlin is an interface that provides read-only access to a collection of elements. It does not allow adding, removing, or changing elements. This makes it safe to share without worrying about accidental changes.

On the other hand, ArrayList is a concrete class implementing MutableList, which extends List by adding methods to modify the collection. It uses a resizable array internally, so it offers fast access and efficient modifications.

Because List is an interface, you can have different implementations like ArrayList, LinkedList, or others. But ArrayList is the most common mutable list used in Kotlin for dynamic collections.

⚖️

Code Comparison

Here is how you create and use a List in Kotlin. Notice you cannot add or remove elements after creation.

kotlin
fun main() {
    val readOnlyList: List<String> = listOf("apple", "banana", "cherry")
    println(readOnlyList[1]) // Access element
    // readOnlyList.add("date") // Error: Unresolved reference
}
Output
banana
↔️

ArrayList Equivalent

Here is how you create and use an ArrayList in Kotlin. You can add, remove, or change elements freely.

kotlin
fun main() {
    val mutableList: ArrayList<String> = arrayListOf("apple", "banana", "cherry")
    mutableList.add("date")
    println(mutableList) // Prints all elements including the new one
}
Output
[apple, banana, cherry, date]
🎯

When to Use Which

Choose List when you want to ensure the collection cannot be changed after creation, which helps avoid bugs and makes your code safer.

Choose ArrayList when you need to add, remove, or update elements dynamically during program execution. It offers good performance for these operations.

In summary, use List for fixed data and ArrayList for flexible, changeable collections.

Key Takeaways

List is read-only and does not allow modification.
ArrayList is mutable and supports adding/removing elements.
List is an interface; ArrayList is a concrete class.
Use List for fixed data and ArrayList for dynamic data.
ArrayList offers fast random access and efficient modifications.