Programming/Kotlin

[Kotlin] ์ฝ”ํ‹€๋ฆฐ mutableList ์ˆ˜์ • ๋ฐ ์‚ญ์ œํ•˜๋Š” ๋ฐฉ๋ฒ•

yuri lee 2023. 1. 16. 23:38
๋ฐ˜์‘ํ˜•

Intro 

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” ์ฝ”ํ‹€๋ฆฐ์—์„œ mutableList ๋ฅผ ์ˆ˜์ • ๋ฐ ์‚ญ์ œํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

MutableList

์ฝ”ํ‹€๋ฆฐ์—์„œ ์ˆ˜์ • ๋ฐ ์‚ญ์ œ ๋“ฑ๊ณผ ๊ฐ™์€ ์ž‘์—…์„ ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” List๊ฐ€ ์•„๋‹Œ, mutableList๋กœ ์„ ์–ธํ•ด์ค˜์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๊ธฐ๋ณธ์ ์œผ๋กœ val, var ๋ณ€์ˆ˜๋ฅผ ์ œ๊ณตํ•˜๊ณ  ์žˆ๋Š”๋ฐ์š”, val๋Š” ์ฝ๊ธฐ๋งŒ ๊ฐ€๋Šฅํ•˜๊ณ , var์€ ์ฝ๊ธฐ ๋ฐ ์ˆ˜์ •์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. 

 

How to do 

์•„๋ž˜ ์ฝ”๋“œ์™€ ๊ฐ™์ด ์ˆ˜์ • ํ˜น์€ ์‚ญ์ œ๊ฐ€ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ์ˆ˜์ •ํ•˜๊ณ  ์‹ถ์„ ๊ฒฝ์šฐ, ํ•ด๋‹น ์ธ๋ฑ์Šค์— ์ƒˆ๋กœ์šด ๊ฐ’์„ ๋„ฃ์–ด์ฃผ๋ฉด ๋˜๊ณ , ์‚ญ์ œ๋ฅผ ํ•˜๊ณ  ์‹ถ์„ ๊ฒฝ์šฐ removeAt() ๋ฉ”์†Œ๋“œ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ์‚ญ์ œํ•˜๊ณ ์ž ํ•˜๋Š” ์ธ๋ฑ์Šค ๋ฒˆํ˜ธ๋ฅผ ๋„ฃ์–ด์ค๋‹ˆ๋‹ค. 

fun main() {
    val list: MutableList<String> = mutableListOf()
    list.add("Apple")
    list.add("Orange")
    list.add("Raspberry")
    list.add("Strawberry")
    list.add("Watermelon")
    list.add("Melon")    
    list.add("Peache")

    println("====== before ======")
    println(list)
    println(list.size)

    println("====== after ======")
    list[1] = "Banana"
    println(list)
    println(list.size)
    list.removeAt(2)
    println(list)
}

 

์ฝ”๋“œ ๊ฒฐ๊ณผ๋Š” ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค. 

====== before ======
[Apple, Orange, Raspberry, Strawberry, Watermelon, Melon, Peache]
7
====== after ======
[Apple, Banana, Raspberry, Strawberry, Watermelon, Melon, Peache]
7
[Apple, Banana, Strawberry, Watermelon, Melon, Peache]

play.kotlinlang.org

 

๋ฐ˜์‘ํ˜•