CodeGym /행동 /Kotlin SELF /Collection saengseong

Collection saengseong

Kotlin SELF
레벨 19, 레슨 0
사용 가능

1. Wae baeyeolman-euro neun gapjagi bujokhaejyeosseulkka

Jigeum “wae tto dareun collection-i piryohaji? naegen baeyeol-i itneunde”라고 saenggakha-go itdamyeon, geuge normalhan ban-eung-imnida. Baeyeol-eun hwaksilhi element suga mi리 al-lyeojyeo itgo geu suga geu리 byeonhaji aneun munje-eseo aju jal matchseumnida. Hajiman “silje” peurogeuraem-eul sseugi sijakhamyeon (“sihom”eul wihan geosi anira), bulpyeonhan sasil-i deureonabnida: hyeonsil-eun gojeong doeneun keugireul silheohamnida.

Ye-reul deureo, console mini-gye-yeong app-eul mandeulyeogo handago haebosipsida (i app-eun kursu jungan-e deo baljeon sikil geos-imnida). Recode-ga myeot gae saenggil까요? 5? 50? 500? Al su eopseumnida. Baeyeol-eul seontaeghamyeon, “manyeok-eul wihayeo” 엄청 keun keugireul 잡거나, element-reul neul릴 ttae마다 baeyeol-eul gyesok saeroun geollo jaesaengseonghaeya 합니다. Dul da byeollo-imnida: hana-neun memori-reul nang비하고 eosaekhae bo이며, dareun hana-neun code-reul “sangja 옮기기 sport”로 mandeul-eo beor립니다.

Baeyeol-eul beonho ga itneun 칸-deul-uro 된 sangja-ro saenggakhagi

Baeyeol-eun 칸(deureul) gateun sangja-ro saenggakhamyeon pyeonhab니다. 각 칸에는 beonho(index)가 itgo, sangja-neun 처음부터 “N gae 칸”으로 한 beon-e 만들어지며, keugireul 키울 수는 eopseumnida: 더 큰 sangja-reul saeroun geollo mandeulgo, geu an-e nallim-eobs-i jeonbu 옮겨 담는 것뿐입니다. Kotlin-eseo baeyeol-eun hang상 mutable입니다: element-neun arr[i] = ... 처럼 바꿀 수 있지만, keugi-neun geudaero입니다. Ijeom-eul 꼭 gieokhaeya 합니다. “mutable baeyeol”은 “keugi-ga neul-eo나는 baeyeol”이 아닙니다.

Baeyeol-i “keugi-reul yujihanda”neun geos-eul boyeojuneun choeso 예시입니다:


fun main() {
    val arr = arrayOf(1, 2, 3)
    println(arr.size) // 3

    arr[0] = 10
    println(arr[0])   // 10
}

Yeogi-seo ganeun 값을 바꾸-eotjiman, keugi-neun 3euro geudaero imnida.

Yejeon-e “baeyeol-eul neullin” bangbeop-gwa wae i-ge jjarijeunji

Baeyeol-e element-reul “chuga”haeya hal ttae, jeongseok-eun keugi-ga deo keun saeroun baeyeol-eul mandeulgo 기존 element-deul-eul 복사하는 것입니다. Agin jeongrihae-do, du뇌-ga gye속 peurogeuraem-ui munje-ga anira memori gyesan-e jirin jiphap-eul sseuge doemnida: “칸이 몇 개지”, “어디로 복사하지”, “index 안 빼먹었나”.

“element hana deouk”eul haneun neukkim-ui 예시입니다 (idea, not final app style):

fun main() {
    var names = arrayOf("Ann", "Bob")
    println(names.contentToString()) // [Ann, Bob]

    names = names.copyOf(names.size + 1)
    names[names.lastIndex] = "Cara"

    println(names.contentToString()) // [Ann, Bob, Cara]
}

Doenayo? Ne. Pyeonhanayo? Byeollo. Geurigo haengbokhan jom: ireohge “chuga”ga man-a-jimyeon code-ga “gye-yeong app”ga anira “baeyeol 이사 manager” gateun 모양이 됩니다.

2. Collection: byeonhaneun keugi-ui container

Collection-eun daeum logical step-imnida: element suga byeonhal su itneun container(0 gaedo, 1000 gaedo)이며, geureomyeonseo chuga, sakje, geomsaek gateun pyeonrihan operation-eul 제공합니다.

Collection-eul sseumyeon, “data-eul eotteohge saeroun sangja-ro 옮길까”보다 “data-reul eotteohge cheoriha-go sipeun-ga”reul deo manhi saenggakhage 됩니다. Egeun peurogeuraeming eoneo-ga silje로 saenghwal-eul pyeonhage mandeuneun sojunghan 지점 중 하나입니다.

Gibon 3 gaji: List, Set, Map

“collection”이라고 하면, bo통 세 gaji keun family-reul tteoolrimnida: list, set, map.

Uimi-ro swipge go르도록, daeum 표를 boramyeon pyeonhab니다:

Type Mueot-eul jeojanghaneun-ga Jungyohan 포인트 Duplicate Jujero eotteohge sseuneun-ga
List<T>
element order wa index 허용 jichul list, 할 일 list, event history
Set<T>
element uniqueness 따로 저장되지 않음 command set, category set, “already seen”
Map<K, V>
key → value pair access by key keys are unique settings, dictionary, “id → object”, counters

Jigeum-eun traversal, sorting, “pyeonrihan operation” deureul deep하게 들어가지 않겠습니다 — geugeon daeum-e. Oneul-ui mokpyo-neun deo dan순합니다: wae collection-i baeyeol-gwa gatji an-eunji, List/Set/Mapi eotteohge dareunji, geurigo eotteohge saengseonghaneunji ihaehaneun 것입니다.

Jungyohan nuance: baeyeol-eun collection-i 아니다

Ijeom-eun 의외로 혼동을 줄여주는 subtle point입니다: Kotlin-eseo baeyeol-eun collection-gwa da-reun 별도의 entity로 취급됩니다. Documentation-eseo도 “baeyeol-eun collection type이 아니다”라고 명시합니다.

Silje로-neun du 가지 의미가 있습니다. Cheot째, baeyeol-eun 자기만의 기능/functor set가 있고, collection-eun 또 다릅니다. Dul째, code-reul 읽을 때 “baeyeol-gwa list-neun just 다른 표기일 뿐 같은 것”이라고 saenggak하지 않는 게 중요합니다. 둘 다 element를 가진다는 점에서 겉모습은 비슷하지만, usage logic은 자주 달라집니다.

3. Read-only vs mutable: wae Kotlin-eun “읽기”wa “변경”을 나누는가

Kotlin-eseo-neun jungyohan idea-ga 있습니다: “type-i geu geos-euro mueot-eul 할 수 있는지 말해준다.” Geuraeseo collection-eun read-only interface-wa mutable interface로 나뉩니다. Igeun “학습자를 괴롭히려는 복잡함”이 아니라, data가 우연히 바뀌는 것을 막아주는 실용적 방어선입니다.

Standard library-eseo, 각 기본 collection 종류마다 interface 쌍이 있습니다: read-only(읽기 전용)와 mutable(읽기 + 변경). Geuraeseo 다음 쌍들이 존재합니다: List/MutableList, Set/MutableSet, Map/MutableMap. Geurinikka “거의 같은 단어 두 개” 같지만, 의미는 다릅니다.

Read-only collection = “i reference로는 변경 불가”

Read-only type(List, Set, Map)은 말 그대로입니다: i variable을 통해서는 변경 operation(add, remove, index assignment 등)을 사용할 수 없습니다. size를 읽고, element를 가져오고, 포함 여부를 확인할 수는 있지만, container 자체를 “재구성”할 수는 없습니다.

Igeun “여기서는 읽기만 한다”라고 명확히 말하고 싶을 때 매우 유용합니다. 예를 들어 함수가 지출 list를 받아 합계를 계산해야 한다면(계산 중에 “실수로 지출 절반을 지워버리는” 일이 없어야 함), read-only가 의도를 지켜줍니다.

“읽기 전용” 예시는 이렇게 보입니다:

fun main() {
    val names: List<String> = listOf("Ann", "Bob", "Ann")
    println(names.size) // 3
    println(names)      // [Ann, Bob, Ann]
}

Yeogi-seo names는 read-only list입니다. Duplicate를 포함할 수 있고, element order도 유지됩니다.

Mutable collection = “내용을 바꿀 수 있음”

Mutable type(MutableList, MutableSet, MutableMap)은 element를 추가/삭제/갱신할 수 있음을 의미합니다.

Gajang 기본 예시:

fun main() {
    val numbers = mutableListOf(1, 2, 3)
    numbers.add(4)

    println(numbers) // [1, 2, 3, 4]
}

바로 여기서 우리가 원했던 “마법”이 일어납니다: sangja를 다시 만들지 않아도 list가 자라났습니다.

val과 “내부 mutability”: 자주 헷갈리는 지점

매우 중요한 규칙 하나가 있습니다. 처음엔 딱 한 번 머리가 아픈데, 한 번 깨닫고 나면 당연해집니다: val은 variable 재할당을 막지만, 그 variable이 참조하는 object 자체를 바꾸는 것까지 막지는 않습니다.

다음 예시를 보고 차이를 느껴보세요:

fun main() {
    val xs = mutableListOf("one", "two", "three")
    xs.add("four")                 // 가능
    println(xs)                    // [one, two, three, four]

    // xs = mutableListOf("X")     // 불가: val은 재할당 불가
}

Igeun 아주 흔한 style입니다: “collection은 mutable, variable은 val”. 즉 “container는 변경할 수 있지만, container object 자체를 실수로 다른 것으로 바꾸지는 못하게 하겠다”라는 의도입니다.

Read-only는 “우주 전체에서 절대 안 바뀜”이 아니다

Tto han beon subtle point: read-only type은 data가 “절대” 바뀌지 않는다고 보장하지 않습니다. “이 특정 reference를 통해서는 변경 method를 호출할 수 없다”만 보장합니다.

Eodiga-e 같은 mutable collection을 가리키는 다른 reference가 있다면, 그쪽에서 변경이 일어날 수 있습니다. I dan-gye에서는 shared reference 같은 복잡한 주제로 들어갈 필요는 없지만, 직관 하나는 기억해두면 좋습니다: read-only는 immutability 마법이 아니라 API 제약입니다.

4. Collection saengseong: listOf, mutableListOf, setOf, mapOf

Jigeumkkaji-neun arrayOf(...)나 IntArray(...)로 baeyeol-eul 만들었습니다. Collection-eun 더 간단합니다: Kotlin에는 값들을 받아 원하는 type을 만들어주는 factory function들이 있습니다. “이 element들로 list를 만들어라”처럼 거의 문장처럼 읽힙니다.

Geurigo ne, i function들은 정말 자주 씁니다: 예제, 문서, 실제 코드에서 계속 보게 될 겁니다. Geuraeseo collection 기반 로직을 본격적으로 쌓기 전에 지금 익숙해지는 게 중요합니다.

listOf(...)와 mutableListOf(...)

listOf(...)는 read-only List를 만듭니다. 바꾸지 않을 “값들의 묶음”이 있을 때 편합니다.

mutableListOf(...)는 크기를 늘리고 줄일 수 있는 MutableList를 만듭니다.

비교를 위해 나란히 본 예시:

fun main() {
    val readOnly = listOf("A", "B", "C")
    println(readOnly)       // [A, B, C]

    val mutable = mutableListOf("A", "B", "C")
    mutable.add("D")
    println(mutable)        // [A, B, C, D]
}

앞으로의 의미 있는 팁(과도한 엄격함 없이): 바꿀지 확신이 없으면 read-only부터 시작하세요. Mutable은 정말로 변경이 필요할 때 선택하면 됩니다.

setOf(...)와 mutableSetOf(...)

setOf(...)는 unique element들의 set을 만듭니다. Element를 실수로 반복해도 set이 “더 길어지지” 않습니다. Set의 핵심은 uniqueness입니다.

Gibon 예시:

fun main() {
    val tags = setOf("kotlin", "kotlin", "jvm")
    println(tags)        // 예: [kotlin, jvm]
    println(tags.size)   // 2
}

Juyi: 출력 순서를 로직의 일부로 삼지 않습니다. Set은 “unique 값들의 주머니”처럼 받아들이면 됩니다.

Mutable variant:

fun main() {
    val commands = mutableSetOf("add", "list")
    commands.add("remove")
    commands.add("add") // 중복
    println(commands)   // [add, list, remove] (중복은 추가되지 않음)
}

mapOf(...), mutableMapOf(...)와 infix function to

Map은 “key → value” 쌍을 저장합니다. Key는 unique합니다.

Map은 to로 만들면 편합니다:

fun main() {
    val prices = mapOf(
        "tea" to 90,
        "coffee" to 150
    )

    println(prices) // {tea=90, coffee=150}
}

mutableMapOf로는 값을 바꾸거나 추가할 수 있습니다:

fun main() {
    val stock = mutableMapOf("apple" to 3)

    stock["apple"] = 4
    stock["banana"] = 1

    println(stock) // {apple=4, banana=1}
}

미리 한 가지는 솔직히 말해두겠습니다: map[key]로 읽으면, key가 없을 때 null이 나올 수 있습니다. 이는 정상적인 안전 모델입니다. 자세한 내용은 Map 강의에서 차분히 다룰 것이고, 지금은 “그럴 수 있다” 정도로만 기억해두세요.

5. Bin collection-gwa type inference: wae compiler-ga hint-reul yocheonghaneun-ga

Collection이 비어 있지 않으면, Kotlin은 보통 element type을 자동으로 추론합니다. Hajiman collection이 비어 있으면 compiler가 “잡을 게” 없습니다: element가 하나도 없으니 무슨 type이어야 하는지 알 수 없기 때문입니다. Geuraeseo bin collection은 흔히 type을 명시해서 만듭니다.

Igeun 실무에서 중요한 포인트입니다: 특히 프로그램이 실행되는 동안 data가 누적되는 앱에서는 bin collection을 계속 만들게 됩니다.

Bin collection-i anin gyeongu: type-i jadong-euro 추론됨

Kotlin이 스스로 type을 이해하는 예시:

fun main() {
    val a = listOf(1, 2, 3)           // List<Int>
    val b = setOf("kotlin", "jvm")    // Set<String>
    val c = mapOf("a" to 1)           // Map<String, Int>

    println(a) // [1, 2, 3]
    println(b) // [kotlin, jvm]
    println(c) // {a=1}
}

여긴 간단합니다: element가 type을 알려줍니다.

Bin collection: type을 지정해야 함

이번에는 bin collection을 올바르게 만들어봅시다:

fun main() {
    val items = mutableListOf<String>()
    val categories = mutableSetOf<String>()
    val counts = mutableMapOf<String, Int>()

    items.add("milk")
    categories.add("food")
    counts["milk"] = 1

    println(items)      // [milk]
    println(categories) // [food]
    println(counts)     // {milk=1}
}

Juyi: 각 줄의 <String> 또는 <String, Int>은 “쓸데없는 소음”이 아니라, compiler에게 주는 힌트입니다. 이 힌트가 없으면 compiler가 맞혀야 할 의무가 없습니다.

6. App mini sketch: wae silje-eseo collection-i piryohan-ga

I nal-buteo, kursu-eseo 실용적인 console app을 만들기 시작합니다(이 단계에서는 class/OO P 없이). “collection을 collection 때문에”라는 느낌이 없도록, 간단한 현실 문제에 연결해봅시다: 사용자 입력으로 들어오는 지출 기록을 저장하는 것. Oneul-eun 딱 시작 부분만 합니다: memory 내 저장소와 몇 가지 동작. Command, 입력 정규화, 완전한 로직은 나중에 다룰 것이고, 지금은 collection이 크기 문제를 해결한다는 걸 보는 것이 중요합니다.

우선 지출 기록을 단순한 string으로 가정해봅시다(예: "food coffee 300"). 네, 아직 이상적인 데이터 모델은 아니지만, 현재 지식 수준에서 정직하고 작동하는 임시 형식입니다.

Baeyeol version: 불편하고 시끄러움

Baeyeol로 “지출 모으기”를 하면(단순화):

fun main() {
    var expenses = emptyArray<String>()

    println("지출을 입력하세요(또는 종료하려면 빈 줄):")
    while (true) {
        val line = readln().trim()
        if (line.isEmpty()) break

        expenses = expenses.copyOf(expenses.size + 1)
        expenses[expenses.lastIndex] = line
    }

    println("저장된 기록 수: ${expenses.size}") // 예: 2
}

동작은 하지만, 느낌상 지출을 다루는 게 아니라 data를 다시 포장하는 것 같습니다.

MutableList version: 더 짧고, 더 깨끗하고, 의미에 가깝다

이제 collection으로 같은 일을 해봅시다:

fun main() {
    val expenses = mutableListOf<String>()

    println("지출을 입력하세요(또는 종료하려면 빈 줄):")
    while (true) {
        val line = readln().trim()
        if (line.isEmpty()) break

        expenses.add(line)
    }

    println("저장된 기록 수: ${expenses.size}") // 예: 2
}

차이는 줄 수만이 아닙니다. 코드를 쓰면서 생각하는 대상이 달라집니다. 여기서는 머릿속에 “기록을 추가한다”가 있고, “배열을 다시 만들고 복사한다”가 없습니다. 이 점 때문에 실무 코드에서 collection을 좋아합니다.

Container reul ppalli 고르는 법: 초보자를 위한 간단한 규칙

Collection을 처음 배우면 “뭘 골라야 하지? list? set? map?”에서 멈추기 쉽습니다. 정상입니다. 성능/내부 구현 깊게 들어가지 않고, 아주 단순한 선택 모델만 고정해둡시다.

순서가 중요하고 중복이 허용되면 대부분 List입니다. 값의 유일성이 필요하면 Set을 쓰세요. “key → value” 대응을 저장하고 key로 찾고 싶으면 Map을 쓰면 됩니다.

Mini flowchart처럼 생각해도 됩니다:

flowchart TD
    A["여러 값을 저장해야 한다"] --> B{"키로 접근해야 하나?"}
    B -->|예| M["Map⟨K, V⟩"]
    B -->|아니오| C{"유일성이 필요한가?"}
    C -->|예| S["Set⟨T⟩"]
    C -->|아니오| L["List⟨T⟩"]

이 도식은 “고급 수학”이 아니지만, 일상적인 대부분의 경우에 빠르게 결정을 내리는 데 도움이 됩니다.

7. Collection-eul 처음 배울 때 자주 하는 실수

Silsu #1: read-only와 immutable을 혼동하기(“List로 바꿀 수 없으면, 그럼 아무도 절대 못 바꾸는 거겠지”).
Read-only type은 특정 reference를 통한 operation만 제한합니다. 다른 곳에 동일 data를 가리키는 mutable reference가 없다고 보장하지는 않습니다. Kursu 초반에는 간단한 규칙만 기억하면 됩니다: read-only는 immutability가 아니라 API/사용 가능 method에 관한 것입니다.

Silsu #2: “혹시 몰라서” mutable collection을 var로 들고 있기.
초보자는 종종 var list = mutableListOf(...)처럼 씁니다. “변경이 있으니까 var겠지”라는 생각 때문입니다. 하지만 변경은 variable 재할당이 아니라 collection method(add, remove)로 일어납니다. 그래서 더 안전하고 편한 스타일은 val list = mutableListOf(...)입니다: collection을 실수로 다른 것으로 바꾸지 못하게 해줍니다.

Silsu #3: type 없이 bin collection을 만들고 compilation error에 놀라기.
mutableListOf()처럼 element 없이 쓰면, compiler는 여러분이 MutableList의 어떤 element type을 원하는지 맞힐 의무가 없습니다. 해결은 간단합니다: type을 명시(mutableListOf<String>(), mutableMapOf<String, Int>())하거나 variable의 기대 type을 지정하세요.

Silsu #4: Set을 “index 없는 list, 나머지는 동일”로 생각하기.
Set은 의미가 다릅니다: uniqueness. Set에서 “첫 번째 원소”, “두 번째 원소”, “추가 순서” 같은 것을 기대하면 로직이 취약해집니다. Oneul 주제 수준에서는 Set을 “unique 값들의 묶음”으로만 다루면 충분합니다.

Silsu #5: listOf/setOf/mapOf를 mutable처럼 업데이트하려고 하기.
listOf, setOf, mapOf factory는 read-only collection을 만듭니다. 내용 변경이 필요하다는 걸 미리 알고 있다면 mutableListOf, mutableSetOf, mutableMapOf를 고르세요. 이는 취향이 아니라, 코드 의도를 명확하게 만드는 방법입니다.

Silsu #6: baeyeol-gwa collection-eul 다른 존재로 보지 않기.
초보자는 arrayOf(...) 다음에 listOf(...)를 보고 “같은 건데 이름만 다른가?”라고 생각하기 쉽습니다. 하지만 baeyeol은 별도 type이며, 고유 규칙이 있습니다(예: baeyeol은 element 기준으로 항상 mutable). Container를 고르는 것은 data와 작업 방식까지 함께 고르는 일이므로, 처음부터 구분을 머리에 두는 편이 좋습니다.

1
과제
Kotlin SELF, 레벨 19, 레슨 0
잠금
두 개의 친구 목록
두 개의 친구 목록
1
과제
Kotlin SELF, 레벨 19, 레슨 0
잠금
실시간 쇼핑 목록
실시간 쇼핑 목록
1
과제
Kotlin SELF, 레벨 19, 레슨 0
잠금
중복 없는 해시태그
중복 없는 해시태그
1
과제
Kotlin SELF, 레벨 19, 레슨 0
잠금
키오스크 가격표
키오스크 가격표
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION