CodeGym /행동 /Kotlin SELF /Setgwa MutableSet — yuilseong gwa sojog yeobu (membership...

Setgwa MutableSet — yuilseong gwa sojog yeobu (membership) geomsaje

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

1. Wae Set i pilyohal까, imi List ga itneunde?

List ga “beonho pyo reul badeun saramdeul ui jul” iramyeon, Set eun “ipgu eseo hwaiginhaneun bangmyeongnok” gatseumnida. Yeogiseo jungyohan geon han 가지 ppun: saram i myeongdan e itgeona, eopgeona. Peurogeuraeming eseoneun i model i aju jaju deungjanghamnida: “heoyong doen command”, “yuilhan tag”, “imi cheori doen 값”, “junggong chu-ga geumji”. Set eun i aidi-eul jikjeop jeok-gi e jinhaenghage haejugo, “chu-ga jeon-e list reul geomsahae bollaeya” gateun bupyeonhan bangbeop e uijonhaji anke haejumnida.

Kotlin gwansjeom eseo, Set<T> eun yuilhan element reul jeojanghamnida: gat-eun 값-eun set an-e “du beon” jonjaehal su eopseumnida. Ttohan botong set eseo neun sunseo ga uimi ui ilbu ga anida 라고 malhamnida. Munseo (documentation) eneun i reul ireoke seolmyeonghamnida: Set eun yuilhan element reul jeojanghago, geu sunseo neun “botong jeongui doeeo itji anta”.

Gandanhan console aep eul mandeureoseo jichul record reul jeojanghago it다고 sangsanghaeboseyo (uri neun jeon gang-ui eseo list reul sayonghae i reul sijakhaetjyo). Eoneu sungan eonjena geureotdeut, da-eum-gwa gateun yogu ga saenggil geosimnida:

  • jichul list reul jeojanghagi (yeogi neun junggong do heoyong: coffee reul 200 beon saneun geon ganeungham);
  • geureomyeonseo do imi deungjanghaetdeon category-ui yuilhan set-eul yujihagi (hint reul boyeojugeona input eul validation hagi wiham).

I geot-i baro Set ui jeongseok sayong cheo-imnida.

2. Set gwa MutableSet: ilkgi wa byeongyeong

Cheoeum Set gwa MutableSet eul bomyeon, da-eumcheoreom saenggakhagi swip습니다: “Ah, Set eun val gateun geo-go, MutableSet eun var gateun geoya.” Geureonde yeogiseo Kotlin eun seuljeok useumnida.

Set<T> — ilkgi yong interface: size, jonjae yeobu hwagin, iteration.
MutableSet<T> — sujeong yong interface: chu-ga, sakje.

Jeuk, cha-i neun byeonsu reul 바꿀 수 itneunya ga anira, type-eul tonghae sayong ganeunhan yeonsan i mueos-inga e it습니다. I style-eun List/MutableList wa gatseumnida.

Tto han 가지 jungyohan point: mutable set-eun daebu-bun val 로 jeojanghaneun geot-i joh습니다. Geureomyeon silsu ro byeonsu ga dareun set-euro “jaehwal-dang (rebind)” doeneun il-eul 막으면서도, naeyong-eun add/remove reul tonghae jeongjikage 바꿀 수 it습니다. I aidi-eun Kotlin collection overview eseo do deungjanghaetjyo: val eun reference reul bohoga hajiman, mutable collection-ui write yeonsan-eul geumjihaji neun anseumnida.

Set saengseong: setOf, mutableSetOf, bin set

Choboja-eseo neun 표준 라이브러리-ui factory function-euro set-eul mandeuneun geot-i gajang pyeonhamnida. Ideul-eun “jigeum 당장 list/set 만들어 줘” cheoreom 읽혀서, bulpil-yo han noseu-ga eopseumnida. Ttohan uri-ga list-eul wihyeo imi sayonghaetdeon listOf(...) wa mutableListOf(...) style-gwa do jal match습니다.

setOf(...) wa jungbok “jeongni” (collapse)

fun main() {
    val tags = setOf("kotlin", "kotlin", "jvm")

    println(tags)        // [kotlin, jvm]
    println(tags.size)   // 2
}

Yeogiseo jungyohan geon set-i eotteon sunseo 로 chulryeokdoeneunya-ga anira, jungbok "kotlin" i du beonjjae element reul mandeulji anneunda-neun 점입니다. Set eun “myot beon deungjanghaetneunji” ga anira, yuilseong-e daehae malhamnida.

Bin set: ttaeron 명시jeog type-i pilyo

List-wa gat-i, bin collection-eun compila-eo ege 힌트가 pilyo hal 때가 man습니다: “yeogi-eun mu슨 type element reul gidaryeoni?”

fun main() {
    val usedCategories = mutableSetOf<String>()

    usedCategories.add("food")
    println(usedCategories) // [food]
}

Man약 mutableSetOf() man sseugo <String> eul ppaemyeon, Kotlin eun jeongjikage malhal su it습니다: “Naneun yeogi-e mueos-eul neoeoya haneunji moreu겠어.” Geu-reogo geu mal-i maj습니다.

3. Set ui gibon yeonsan

Yuilseong-e 대한 contract: add() 와 banhwan doeneun Boolean

List-eseo add() neun daebu-bun “element-ga hwaksilhi (kkeun-e) chu-ga doeeotda” reul uimi합니다. Set-eseoneun deo heungmi롭습니다: add(x) 는 “chu-ga reul 시도하되, imi gat-eun element-ga iteu면 amugeotdo 바꾸지 ma” reul uimi합니다. Geuraeseo i yeonsan-eun Boolean eul banhwan합니다: jeongmal 새 element-ga chu-ga doeeotneunya.

I geot-eun “han beon man allyeoju-gi” na “dongilhan haengdong jungbok geumji” reul 하고 싶을 때 aju yuyong합니다.

fun main() {
    val seen = mutableSetOf<Int>()

    println(seen.add(10)) // true
    println(seen.add(10)) // false
    println(seen)         // [10]
}

Dubeonjjae 시도에서는 “du beon-jjae 10” eul chu-ga하지 않습니다 — set-ui uimi-reul bogo geureoke hal pilyo-ga eopseumnida.

Sojog yeobu hwagin: contains() wa in yeonsanja

Set 에서 gajang “jayeonseureoun” yeonsan-eun i jilmun입니다: “I element-ga yeogi itna?” Kotlin-eseo-neun i reul dubeon-gaji dongdeunghage olbareun bangbeop-euro 할 수 it습니다: contains(x) 로, tto는 x in set 로. Dubeonjjae bangbeop-i botong deo jal 읽히며, teukhi 조건문에서 geureoh습니다.

Geuligo, i geot-i baro set-eul “heoyong/biheoyong” geomsaje aejong하는 iyu jung hana입니다: code-ga geoui malcheoreom 변합니다.

fun main() {
    val allowedCommands = setOf("add", "list", "remove")

    val cmd = "list"
    println(cmd in allowedCommands) // true
}

Yeogiseo nun-e ttuige du-go sipeun image-neun i geot입니다: Set eun “heoyong doen 값-deul ui jiphap”. Sunseo-e do, index-e do, geurigo “3 beonjjae element sakje” 같은 geot-e do jeoldae gwan-yeon eopseumnida.

Sakje: remove() 와 geu banhwan 값

MutableSet 에서 sakje-neun list-ui remove(value) 와 bi슷하지만, uimi-sang deo jayeonseureoun데: set-eun index-ga eopseunikka, sakje-neun hangsang “값-euro” 합니다. add 와 gat-i, i yeonsan do Boolean eul banhwan합니다: jeongmal mueonga ga sakje doeeotneunya.

fun main() {
    val usedCategories = mutableSetOf("food", "transport")

    println(usedCategories.remove("food")) // true
    println(usedCategories.remove("food")) // false
    println(usedCategories)                // [transport]
}

Dubeonjjae-neun sakjehal geot-i eopseumnida — "food" 는 imi eopseumnida.

4. Sunseo, dongdeungham (equality), geurigo “junggong ppaegi”

Set 에서 sunseo-e 의존해도 doel까?

Gaeinsijeog-euro-neun ireon saenggak-i deulgi 쉽습니다: “Chulryeok-i "[a, b, c]" cheoreom doenee? geureom sunseo-ga itneun 거 아냐?” Geuligo Kotlin eun silje-ro set-eul da루-l 때 sunseo-ga an-jeongjeog-in geot cheoreom boye ju-neun gyeongu-ga man습니다. Hajiman yeogiseo-neun “oneul eotteoke 구현되어 itneunya” wa “data structure-ui uimi-ga mueos-inga” reul 구분해야 합니다.

Hyeongsikjeog-euro Set eun set입니다: yuilhan element, geurigo sunseo-neun “byeollo jungyohaji anta”.
Geurimde standard library-eseo Kotlin-ui 기본 MutableSet 구현은 LinkedHashSet 인 gyeongu-ga manhgo, igeo-neun insertion order-reul 유지하므로, first() 와 last() 가 “i 구현” 에서는 예측 가능할 수 it습니다.

Choboja-ege yuyonghan silmu gyuchik-eun i geot입니다: Set 을 sunseo-ga contract-ga anin container 로 daehaeseyo. Element sunseo-ga 바뀌면 로직이 무너진다면 — dae부분 list (ttoneun dareun 구조)가 pilyohan gyeongu-ga man습니다.

“Junggong ppaegi”: toSet() 를 ppalli yuilseong filter 로 sayonghagi

Gajang jaju inneun 적용 scenario han 가지: imi junggong-i inneun list (ttoneun array) ga 있고, yuilhan 값-eul moj-eun set-i pilyohal 때입니다. Yeb-eul deulmyeon, yongho (category) 를 user-ga mameotdaero ipryeokhaet고, geu gyeolgwa-eseo “modeun yuilhan category list” reul eotgo 싶을 때입니다.

Ireul wihayeo toSet() ga it습니다. I function eun saeroun collection-eul mandeulgoseo junggong-eul “jeongri (collapse)” 합니다. Jungyohan 점은, toSet() 처럼 복사/변환 function-eun 호출 시점 ui snapshot-eul 만든다는 것입니다: igeul 만든 뒤 원본 collection-eul 바꿔도, gyeolgwa ga “majik cheoreom” 따라 바뀌지 neun 않습니다.

fun main() {
    val words = listOf("a", "b", "a", "c")
    val uniqueWords = words.toSet()

    println(uniqueWords)      // [a, b, c]
    println(uniqueWords.size) // 3
}

Array-do dongilhi 적용됩니다: array-reul Set 으로 바꾸면 junggong-i 사라지는 geot-eul 볼 수 있고, List 로 바꾸면 — junggong-i 그대로 남습니다.

Set ui dongdeungham: sunseo 보다 element-ga deo jungyo

List-neun dongdeungham-i sunseo-e 의존합니다: [1, 2] 는 [2, 1] gwa gatji 않습니다. Set-neun 논리가 다릅니다: element-ga 같으면, “dareun sunseo 로 만들었더라도” set-eun 같다고 봅니다. I geot-i suhakjeog set-ui uimi-e bu합하며, siljeon-eseo do heoyong권/태그/feature set-eul bigyo할 때 yuyong합니다.

Kotlin munseo-eseo do i reul yebsi-ro 보여줍니다: set-eun gat-eun element-deul-eul 가지면 dongdeung합니다.

fun main() {
    val a = setOf(1, 2, 3, 4)
    val b = setOf(4, 3, 2, 1)

    println(a == b) // true
}

5. Yebsi: jichul gwanri wa yuilhan category

Ije uri-neun oneul mini project-reul 계속해봅시다: “console jichul gwanri”, class-do eopgo bok잡한 architecture-do eopsi — geunyang collection-eul ikeuneun gam각-eul gildeurigi wihan yongdo입니다. Jeon gang-ui-eseo uri-neun jichul record reul MutableList<Triple<String, String, Int>> 에 jeojanghaet고, field-neun category, description, amount 였습니다.

Ije han 가지 구조 reul deo chu-ga hamnida: imi deungjanghaetdeon yuilhan category-reul wihae MutableSet<String>. Ireumyeon du 가지 yuyonghan geot-eul eot습니다: “category-ga imi it-eossna?” reul ppalli al su 있고, eotteon sungan-eseo든 “junggong eomneun category list” reul eot-eul su itseumnida — list jeonche-reul su-dong-euro dola-myeo cheori하지 않아도 됩니다.

Mini data schema

Maeu 간단한 schema-reul geuryeoboseyo. Meori-ga modeun geot-eul giyeokharyeogo 애쓰지 않게 (memory-neun 비싸죠, teukhi woryoil achim-eneun 더…):

flowchart LR
    Records["records: MutableList⟨Triple⟨Category, Title, Amount⟩⟩"]
    Categories["knownCategories: MutableSet⟨Category⟩"]

    Records -->|"dahae record 추가함"| Categories

Aidi: saeroun record-ga 들어올 때마다, saeroun category-ga set-e chugadoel su it습니다. Iji imi itdeon category라면 — set-eun geunyang byeonhaji 않습니다.

Code: record 추가 wa category set eobdeiteu

Yeogiseo-neun uidojeog-euro jageun function-gwa jjalbun yebsi-ro sseumnida. Code-ga “gyojae” cheoreom 읽히게 하려는 겁니다. “Real-world prod” neun 언젠가 dae-shin ttarawa dang-yeon히 잡을 겁니다.

fun addExpense(
    records: MutableList<Triple<String, String, Int>>,
    knownCategories: MutableSet<String>,
    category: String,
    title: String,
    amount: Int
) {
    records.add(Triple(category, title, amount))
    knownCategories.add(category)
}

Juyeohae boseyo: knownCategories.add(category) 는 category-ga imi it-eoss더라도 amugeotdo 망가뜨리지 않습니다. Set-ui 매력 i yeogi 있습니다: contract 자체로 junggong-eul 막아줍니다.

add() 로 “saeroun category인지” hwagin하기

Ije add 가 Boolean eul banhwanhaneun jeom-eul sayonghaeseo, user (ttoneun 디버깅 중인 자기 자신) 에ge yuyonghan message reul chulryeokhaebop시다: saeroun category인지 아닌지.

fun addCategoryIfNew(knownCategories: MutableSet<String>, category: String) {
    val added = knownCategories.add(category)

    if (added) {
        println("New category: $category") // for example: New category: food
    } else {
        println("Category already existed: $category") // for example: Category already existed: food
    }
}

List-neun i geot-eul “out of the box” 로 해주지 않습니다: list-eseo-neun contains 를 따로 하고, 그 다음 add 를 해야 해서, silsu 하기도 쉽고 (ttoneun geunyang 잊어버리기도 쉽습니다).

Wanjeonhan mini yebsi: records wa categories

Aidi jeonche-reul boyeojuneun jageun main 을 모아봅시다. Wanjeonhan UI-reul mokpyo-ro 하지 않습니다 — i geot-eun hak습용 “sandbox” 로, data structure-ga 약속한 대로 동작하는지 직접 확인하는 용도입니다.

fun main() {
    val records = mutableListOf<Triple<String, String, Int>>()
    val knownCategories = mutableSetOf<String>()

    addExpense(records, knownCategories, "food", "coffee", 300)
    addExpense(records, knownCategories, "transport", "taxi", 1200)
    addExpense(records, knownCategories, "food", "lunch", 550)

    println(records.size)              // 3
    println(knownCategories)           // [food, transport] (order is not a contract)
    println("food" in knownCategories) // true
}

Yeogiseo-neun aju jal boyeojumnida: record-neun 3gae (geu jung 2gae-neun "food" category) ijiman, category-neun 2gae ppun입니다 — wae냐hamyeon set-eun yuilhan 값 man jeojang하기 때문입니다.

6. Set gwa null: ne, 가능하지만 — josim

Ttaeroneun data-ga “dirty” 하게 들어옵니다: category parsing-i sil패했거나, user-ga 빈 munjae열-eul 넣었거나, 아직 정리하지 못한 상태일 수 있습니다. Null-safety reul imi 배웠으니, 알아두면 좋은 점: Set 은 null 을 jeojanghal su it습니다. Hajiman yuilhan element 로서 — set 안에는 null 이 최대 한 개만 존재할 수 있습니다. Documentation-edo null 이 Set 안에서도 yuil하다고 말합니다: dubeonjjae null 은 saenggiji 않습니다.

I geot-eun null 을 “ganeunghamyeon modu 넣어라” 라는 권유가 아닙니다 (uri-neun munje reul collection하지 않습니다), hajiman 디버깅 과 transition state-eseo yuyong한 지식입니다.

fun main() {
    val categories: MutableSet<String?> = mutableSetOf()

    categories.add(null)
    categories.add(null)

    println(categories.size) // 1
    println(categories)      // [null]
}

7. Set gwa MutableSet sayong 시 jaju 하는 silsu

Silsu 1: set-i list 처럼 junggong-eul jeojanghaneun geos-euro 기대하기.
Choboja-deul-eun gat-eun 값-eul MutableSet 에 yeoreo beon 넣고 size-ga an neul-eoseo 놀라곤 합니다. I유는 간단합니다: Set 은 uimi-sang yuil한 element man jeojang합니다. Man약 “user-ui modeun 입력” 을 그대로 저장해야 한다면 (junggong-i itde라도), geu geot-eun list-ui yeokhal입니다. Banhae, “mueos-i deungjanghaet었는지” 만 알고 싶다면 — geu geot-eun set-ui yeokhal입니다.

Silsu 2: Set element sunseo-e 의존하는 로직 sseugi.
Ttaeroneun sunseo-ga inneun geot cheoreom boyeoseo, “cheot beonjjae element-eul gajang jungyo han geos-euro 두자” reul 하고 싶어집니다. Kotlin-eseo-neun insertion order-reul yujihaneun 구현이 jaju 쓰이지만, Set ui 본질은 geu geot-i 아닙니다. Sunseo-e 의존하기 sijakhamyeon code-ga yakhajyeo: 구현이 바뀌거나, data source-ga 바뀌면, haengdong-i yeongsanghan 방식으로 바뀔 수 있습니다.

Silsu 3: Set eul index 로 접근하려고 하기.
List reul 쓰고 나면 mySet[0] 같은 geot-eul 쓰고 싶어집니다. Hajiman set-eun model 자체에 index-ga 없습니다. I geot-eun task-e daehae jal못된 container-reul go-reut다는 신호입니다. 위치가 pilyohamyeon List. Yuilseong gwa “itna/eopna” geomsaje-ga pilyohamyeon Set.

Silsu 4: add/remove ga Boolean eul banhwanhaneun geot-eul 잊고, yuyonghan jeongbo-reul 놓치기.
Manh-eun saramdeul-i geunyang add(x) reul 호출하고 gyeolgwa-reul 보지 않는데, sil은 geu geot-i “byeonhwa-ga iss었는지” reul 알려주는 거의 공짜 힌트입니다. Input validation-eul 하거나 “imi 봤던 값” 목록을 관리할 때, i Boolean 이 code-reul 더 dan순하고 명확하게 만들어줍니다: “cheoeum chu-ga doeeotdamyeon — allyeo주거나 행동하고, 아니면 — 건너뛰자.”

Silsu 5: type eopsi bin mutableSetOf() reul mandeulgo compile error-reul 받기.
Bin collection-eun compiler-ege 힌트가 eopseumnida. Geuraeseo ttaeroneun type-eul 명시해야 합니다: mutableSetOf<String>(). I geot-eun jeong상이며, “na쁜 programmer” ran 뜻이 아닙니다. O히려 ban대로, contract-eul 명확히 고정하는 것이고, Kotlin-i 더 이상 추측하지 않게 됩니다.

1
과제
Kotlin SELF, 레벨 19, 레슨 2
잠금
명령어 검사
명령어 검사
1
과제
Kotlin SELF, 레벨 19, 레슨 2
잠금
중복 없는 단어
중복 없는 단어
1
과제
Kotlin SELF, 레벨 19, 레슨 2
잠금
게스트 등록
게스트 등록
1
과제
Kotlin SELF, 레벨 19, 레슨 2
잠금
구독 콘솔
구독 콘솔
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION