Kotlin 简明教程

Kotlin - Collections

对于大多数编程语言来说,集合都是一个常见概念。集合通常包含许多相同类型的对象,并且集合中的对象称为元素或项。

Collections are a common concept for most programming languages. A collection usually contains a number of objects of the same type and Objects in a collection are called elements or items.

Kotlin 标准库提供了一套用于管理集合的全面工具。以下集合类型与 Kotlin 相关:

The Kotlin Standard Library provides a comprehensive set of tools for managing collections. The following collection types are relevant for Kotlin:

  1. *Kotlin List - * List is an ordered collection with access to elements by indices. Elements can occur more than once in a list.

  2. *Kotlin Set - * Set is a collection of unique elements which means a group of objects without repetitions.

  3. *Kotlin Map - * Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value.

Kotlin Collection Types

Kotlin 提供以下类型的集合:

Kotlin provides the following types of collection:

  1. Collection or Immutable Collection

  2. Mutable Collection

Kotlin Immutable Collection

Immutable集合或简单地调用Collection接口提供了只读方法,意味着一旦创建了集合,我们便无法更改它,因为没有方法可以更改创建的对象。

Immutable Collection or simply calling a Collection interface provides read-only methods which means once a collection is created, we can not change it because there is no method available to change the object created.

Collection Types

Methods of Immutable Collection

List

listOf() listOf<T>()

Map

mapOf()

Set

setOf()

Example

fun main() {
    val numbers = listOf("one", "two", "three", "four")

    println(numbers)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

[one, two, three, four]

Kotlin Mutable Collection

可变集合提供了读写方法。

Mutable collections provides both read and write methods.

Collection Types

Methods of Immutable Collection

List

ArrayList<T>() arrayListOf() mutableListOf()

Map

HashMap hashMapOf() mutableMapOf()

Set

hashSetOf() mutableSetOf()

Example

fun main() {
    val numbers = mutableListOf("one", "two", "three", "four")

    numbers.add("five")

    println(numbers)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

[one, two, three, four, five]