이동식 저장소

mutableMapOf()의 내부 구현 본문

Primary/Kotlin

mutableMapOf()의 내부 구현

해스끼 2024. 2. 3. 20:15

Kotlin의 ``mutableMapOf()`` 함수는 내부적으로 ``LinkedHashMap()``을 반환한다.

/**
 * Returns an empty new [MutableMap].
 *
 * The returned map preserves the entry iteration order.
 * @sample samples.collections.Maps.Instantiation.emptyMutableMap
 */
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <K, V> mutableMapOf(): MutableMap<K, V> = LinkedHashMap()

 

Kotlin ``LinkedHashMap``은 Java의 ``LinkedHashMap``으로 ``typealias``되어 있다. 이제 Java의 ``LinkedHashMap`` 구현을 살펴보자.

@SinceKotlin("1.1")
public actual typealias LinkedHashMap<K, V> = java.util.LinkedHashMap<K, V>

Java LinkedHashMap

Java의 ``LinkedHashMap``은 ``HashMap``과 유사하다. 따라서 삽입, 탐색, 삭제 모두 로그 시간이 걸린다.

 

그러나 원소의 순회 순서가 일정하지 않은 ``HashMap``과 달리, 내부적으로 링크드리스트를 활용하여 원소를 삽입 순서대로 순회할 수 있다. 지금까지 ``mutableMapOf()``로 얻은 ``MutableMap``의 순회 순서가 predictable한 것도 모두 ``LinkedHashMap`` 구현체를 사용했기 때문이었다.

참고

 

LinkedHashMap (Java SE 17 & JDK 17)

Type Parameters: K - the type of keys maintained by this map V - the type of mapped values All Implemented Interfaces: Serializable, Cloneable, Map public class LinkedHashMap extends HashMap implements Map Hash table and linked list implementation of the M

docs.oracle.com

 

'Primary > Kotlin' 카테고리의 다른 글

[Kotlin] Coroutines Job  (0) 2022.11.10
[Kotlin] Dispatcher  (0) 2022.11.08
[Kotlin] Computed Property  (0) 2022.10.06
[Kotlin] Coroutine 테스트 디버깅 후기  (0) 2022.07.30
Kotlin Immutable Collections  (0) 2022.07.29
Comments