Hanbit the Developer

Kotlin Documentation | Collections overview 본문

Mobile/Kotlin

Kotlin Documentation | Collections overview

hanbikan 2023. 5. 24. 13:41

Kotlin Documentation 시리즈에 대해

Category: Standard library - Collections

문서 링크: https://kotlinlang.org/docs/collections-overview.html


Collection types

각 인터페이스는 아래의 타입으로 나뉜다.

  • read-only collection
    • covariant(out)
  • mutable collection
    • 굳이 var를 쓰지 않아도 된다.(대입 연산자가 아니라 메소드를 통해 컬렉션을 수정하므로)
    • covariant가 아니다.

Collection

읽기 전용 컬렉션의 공통 행위를 정의하며, List와 Set의 상위 인터페이스이다.

fun printAll(strings: Collection<String>) {
    for(s in strings) print("$s ")
    println()
}
    
fun main() {
    val stringList = listOf("one", "two", "one")
    printAll(stringList)
    
    val stringSet = setOf("one", "two", "three")
    printAll(stringSet)
}

List

List는 인터페이스이기 때문에 초기화 시 실제 구현체가 따로 존재한다:

  • listOf() returns EmptyList(internal object)
  • listOf(element: T) returns new SingletonList(static class)
  • listOf(varargs elements: T) returns elements.asList() which is an expect fun

MutableList 또한 인터페이스이며, 기본 구현체는 ArrayList이다.

Set

특징:

  • 일반적으로 순서가 보장되지 않음
  • null 또한 하나의 원소로 취급됨

Set도 인터페이스이며 위 List와 유사하게 구현체가 존재한다.

인터페이스 MutableSet의 기본 구현체인 LinkedHashSet는 순서를 보장한다.

또 다른 구현체인 HashSet는 순서를 보장하지 않지만 메모리를 적게 쓰게 된다.

Map

Collection의 구현체는 아니다.

val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)

println("All keys: ${numbersMap.keys}")
println("All values: ${numbersMap.values}")
if ("key2" in numbersMap) println("Value by key \\"key2\\": ${numbersMap["key2"]}")    
if (1 in numbersMap.values) println("The value 1 is in the map")
if (numbersMap.containsValue(1)) println("The value 1 is in the map") // same as previous

to: public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)

*infix: 두 개의 변수 가운데 올 수 있는 함수

Map는 인터페이스이며, List, Set과 유사하게 구현체가 존재한다.

인터페이스 MutableMap의 기본 구현체인 LinkedHashMap 또한 순서를 보장한다.

또 다른 구현체인 HashMap는 또한 순서를 보장하지 않는다.