📜  Kotlin ArrayList(1)

📅  最后修改于: 2023-12-03 15:32:29.722000             🧑  作者: Mango

Kotlin ArrayList

Introduction

An ArrayList is a resizable array implementation of the List interface in Kotlin. It can store elements of any type and provides various methods to add, remove, and access elements in the list. It also has the ability to dynamically adjust its size as elements are added or removed.

Creating an ArrayList

To create an ArrayList, we can simply use the ArrayList constructor.

val arrayList = ArrayList<String>()

In this example, we created an ArrayList that can store elements of type String.

We can also provide an initial capacity for the ArrayList if we know how many elements we will be adding.

val arrayList = ArrayList<String>(10)

This creates an ArrayList with an initial capacity of 10.

Adding elements

We can add elements to an ArrayList using the add method.

arrayList.add("foo")

This adds the element "foo" to the end of the ArrayList.

We can also insert an element at a specific index using the add method with an index parameter.

arrayList.add(1, "bar")

This inserts the element "bar" at index 1.

Removing elements

We can remove elements from an ArrayList using the remove method.

arrayList.remove("foo")

This removes the element "foo" from the ArrayList.

We can also remove an element at a specific index using the removeAt method.

arrayList.removeAt(1)

This removes the element at index 1.

Accessing elements

We can access elements in an ArrayList using the get method.

val element = arrayList.get(0)

This gets the element at index 0.

We can also set an element at a specific index using the set method.

arrayList.set(1, "baz")

This sets the element at index 1 to "baz".

Looping through an ArrayList

We can loop through an ArrayList using a for loop.

for (element in arrayList) {
    println(element)
}

This loops through every element in the ArrayList and prints it to the console.

We can also use a forEach loop.

arrayList.forEach { element ->
    println(element)
}

This loops through every element in the ArrayList and prints it to the console.

Conclusion

The ArrayList is a powerful data structure in Kotlin that provides an efficient way to store and access elements. Its dynamic resizing feature makes it a great choice when the size of the list is unknown or changes frequently.