Kotlin

์ฝ”ํ‹€๋ฆฐ Kotlin java.util.ConcurrentModificationException ์—๋Ÿฌ

๋…ธ๋ฃจ๋ฃฝ 2024. 7. 11. 19:55

๊ทธ๋ ‡๋‹ค.

 

์ด ๊ธ€์€ ๋ฐฉ๊ธˆ ์ฝ”ํ…Œ์—์„œ ์ € ์—๋Ÿฌ๋ฅผ ๋ณด๊ณ  ์ฒ˜์Œ ๋ณด๋Š” ์—๋Ÿฌ๋ผ ๋‹นํ™ฉํ–ˆ๊ณ ,

๋กœ์ง์€ ๋‹ค ์งฐ๋Š”๋ฐ ์ €๊ฒƒ ๋•Œ๋ฌธ์— ๋ฌธ์ œ๋ฅผ ๋ชป ํ’€์–ด์„œ ๋ถ„๋…ธ์— ์ฐจ์„œ ์“ฐ๋Š” ๊ธ€์ด๋‹ค.

 

 java.util.ConcurrentModificationException ์ด๋ž€^^!!

์ฃผ๋กœ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๋™์‹œ์— ์ˆ˜์ •ํ•  ๋•Œ ๋ฐœ์ƒํ•˜๋Š” ์—๋Ÿฌ์ด๋‹ค.

 

๋‚˜๊ฐ™์€ ๊ฒฝ์šฐ์— list๋ฅผ for๋ฌธ์œผ๋กœ ๋Œ๋ฆฌ๋ฉด์„œ, 

tempList = list๋ฅผ ์„ ์–ธํ–ˆ๋Š”๋ฐ,

์ด๊ฒƒ์ด ๋ฌธ์ œ์˜€๋‹ค..๐Ÿ˜ต

 

์ดํ•ด๊ฐ€ ์‰ฝ๋„๋ก ์ฝ”๋“œ๋ฅผ ๋ณด์ž!

 

list ๋งจ ์•ž์˜ element๋ฅผ ๋งจ๋’ค๋กœ ์˜ฎ๊ธฐ๋Š” ์ž‘์—…์„ ๋ฐ˜๋ณตํ•˜๋Š” ๋กœ์ง์ด๋‹ค.

fun solution(list: MutableList<Int>) {
    for ((i, element) in list.withIndex()) {
        val tempList = list
        val firstElement = tempList.removeAt(0)
        tempList.add(firstElement)
    }
}

 

3๋ฒˆ์งธ ์ค„์„ ๋ณด์•„๋ผ . .

๋ฉ์ฒญํ•œ ๋‚˜ . . ๐Ÿคฆ‍โ™€๏ธ

 

์ €๋ ‡๊ฒŒ ์„ ์–ธํ•˜๋ฉด tempList๋„ list์™€ ๊ฐ™์€ ๊ณณ์„ ๊ฐ€๋ฆฌํ‚ค๋ฏ€๋กœ

for๋ฌธ์œผ๋กœ list๋ฅผ ์ˆœํšŒํ•˜๋Š” ๊ฑด tempList๋ฅผ ์ˆœํšŒํ•˜๋Š” ๊ฑฐ๋‚˜ ๋งˆ์ฐฌ๊ฐ€์ง€๊ฐ€ ๋œ๋‹ค.

 

๊ทธ๋ž˜์„œ ConcurrentModificationException์ด ๋ฐœ์ƒํ–ˆ๋˜ ๊ฒƒ์ด๋‹ค.

 

์ด๋ฅผ ํ•ด๊ฒฐํ•  ๋ช‡ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•๋“ค์ด ์žˆ๋‹ค.

 

1. ์ž„์‹œ ๋ฆฌ์ŠคํŠธ ์„ ์–ธ

fun solution(list: MutableList<Int>) {
    for ((i, element) in list.withIndex()) {
        val tempList = mutableListOf(list) // mutableList๋ฅผ ์ƒˆ๋กœ ์„ ์–ธ
        val firstElement = tempList.removeAt(0)
        tempList.add(firstElement)
    }
}

 

๋‚ด๊ฐ€ ํ•ด๊ฒฐํ•œ ๋ฐฉ๋ฒ•์ด๋‹ค.!

๋‚ด์šฉ๋ฌผ(?)์€ ๋˜‘๊ฐ™์ง€๋งŒ ๋‹ค๋ฅธ collection์„ ์„ ์–ธํ•ด ์ฃผ๋Š” ๊ฒƒ์ด๋‹ค.

 

 

2. indices ์‚ฌ์šฉ

fun solution(list: MutableList<Int>) {
    for (i in list.indices) {
        val firstElement = list.removeAt(0)
        list.add(firstElement)
    }
}

 

๋งŒ์•ฝ list์˜ element๊ฐ€ ํ•„์š” ์—†๋‹ค๋ฉด, ์ด ๋ฐฉ๋ฒ•์ด ํšจ์œจ์ ์ด๋‹ค.

 

indices ํ•จ์ˆ˜์˜ ๋‚ด๋ถ€๋ฅผ ์‚ดํŽด๋ณด๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

public val Collection<*>.indices: IntRange
    get() = 0..size - 1

 

์ฆ‰, list์˜ ์ธ๋ฑ์Šค(IntRange)๋กœ ์ ‘๊ทผํ•˜๋Š” ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— ์ง์ ‘ list๋ฅผ ์ˆœํšŒํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ฏ€๋กœ

ConcurrentModificationException์ด ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค.

 

 

 

list์˜ element๊ฐ€ ํ•„์š”ํ•  ๋• 1๋ฒˆ ๋ฐฉ๋ฒ•์„

์•„๋‹ˆ๋ฉด 2๋ฒˆ ๋ฐฉ๋ฒ•์„ ์“ฐ๋ฉด ๋  ๊ฒƒ ๊ฐ™๋‹ค.

 

๐Ÿฅน