코틀린

[코틀린 Kotlin] 컬렉션 - 읽기전용 - listOf(), setOf(), mapOf() vs 변경 가능한 - mutableListOf(), mutableSetOf(), mutableMapOf()

멋쟁휘개발자 2024. 9. 8. 21:07

컬렉션을 읽기 전용(read-only)과 변경 가능한(mutable) 두 가지로 관리

  • 읽기 전용 컬렉션은 한 번 생성된 이후에는 수정할 수 없음
  • 변경 가능한 컬렉션은 생성 후에 요소를 추가하거나 제거하는 등의 수정이 가능

읽기 전용 컬렉션

읽기 전용 컬렉션은 수정할 수 없는 컬렉션입니다. 컬렉션을 생성할 때 listOf(), setOf(), mapOf()와 같은 함수를 사용하여 만들 수 있습니다. 읽기 전용 컬렉션은 요소를 읽는 것만 가능하고, 추가하거나 삭제하는 것은 불가능합니다.

fun main() {
    val listOfNumbers = listOf(1, 2, 3)
    println(listOfNumbers[1]) // 2
    // listOfNumbers.add(4) // ERROR: 읽기 전용 컬렉션에는 요소를 추가할 수 없음

    val setOfNumbers = setOf(1, 2, 3)
    // setOfNumbers.add(4) // ERROR: 읽기 전용 컬렉션에는 요소를 추가할 수 없음

    val mapOfNumbers = mapOf(1 to "one", 2 to "two", 3 to "three")
    // mapOfNumbers.put(4, "four") // ERROR: 읽기 전용 컬렉션에는 요소를 추가할 수 없음
}

변경 가능한 컬렉션

변경 가능한 컬렉션은 요소를 추가하거나 제거할 수 있는 컬렉션입니다. mutableListOf(), mutableSetOf(), mutableMapOf()와 같은 함수를 사용하여 생성할 수 있습니다.

fun main() {
    val mutableListOfNumbers = mutableListOf(1, 2, 3)
    mutableListOfNumbers.add(4) // OK: 변경 가능한 리스트에 요소 추가 가능
    println(mutableListOfNumbers) // [1, 2, 3, 4]

    val mutableSetOfNumbers = mutableSetOf(1, 2, 3)
    mutableSetOfNumbers.add(4) // OK: 변경 가능한 셋에 요소 추가 가능
    println(mutableSetOfNumbers) // [1, 2, 3, 4]

    val mutableMapOfNumbers = mutableMapOf(1 to "one", 2 to "two")
    mutableMapOfNumbers[3] = "three" // OK: 변경 가능한 맵에 요소 추가 가능
    println(mutableMapOfNumbers) // {1=one, 2=two, 3=three}
}

읽기 전용 컬렉션을 변경 가능한 컬렉션으로 변환

기존의 읽기 전용 컬렉션을 변경 가능한 컬렉션으로 변환할 수 있습니다. 이 경우 toMutableList(), toMutableSet(), toMutableMap() 메서드를 사용합니다.

fun main() {
    val listOfNumbers = listOf(1, 2, 3)
    val mutableListOfNumbers = listOfNumbers.toMutableList()
    mutableListOfNumbers.add(4) // OK: 읽기 전용 리스트를 변경 가능한 리스트로 변환 후 수정 가능
    println(mutableListOfNumbers) // [1, 2, 3, 4]

    val setOfNumbers = setOf(1, 2, 3)
    val mutableSetOfNumbers = setOfNumbers.toMutableSet()
    mutableSetOfNumbers.add(4) // OK: 읽기 전용 셋을 변경 가능한 셋으로 변환 후 수정 가능
    println(mutableSetOfNumbers) // [1, 2, 3, 4]

    val mapOfNumbers = mapOf(1 to "one", 2 to "two")
    val mutableMapOfNumbers = mapOfNumbers.toMutableMap()
    mutableMapOfNumbers[3] = "three" // OK: 읽기 전용 맵을 변경 가능한 맵으로 변환 후 수정 가능
    println(mutableMapOfNumbers) // {1=one, 2=two, 3=three}
}

요약

  • 읽기 전용 컬렉션: listOf(), setOf(), mapOf()로 생성. 수정할 수 없음.
  • 변경 가능한 컬렉션: mutableListOf(), mutableSetOf(), mutableMapOf()로 생성. 수정 가능.
  • 변환: toMutableList(), toMutableSet(), toMutableMap()을 사용하여 읽기 전용 컬렉션을 변경 가능한 컬렉션으로 변환 가능.