kotlin Exception「Exception in thread “main” java.lang.IndexOutOfBoundsException: toIndex = x」の解決方法

kotlin Exception「Exception in thread “main” java.lang.IndexOutOfBoundsException: toIndex = x」の解決方法

kotlinで、Exception「Exception in thread “main” java.lang.IndexOutOfBoundsException: toIndex = x」の解決方法を記述してます。

環境

  • OS windows11 home
  • java 17.0.2
  • kotlin 1.6.10-release-923

エラー全文

以下のコードで発生。

fun main() {

    var list = mutableListOf("aaa", "bbb", "ccc", "ddd", "eee")
    
    println(list.subList(0, 6))

}

Exception
※ファイル名は「hello.kt」

Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 6
        at java.base/java.util.AbstractList.subListRangeCheck(AbstractList.java:507)
        at java.base/java.util.AbstractList.subList(AbstractList.java:497)
        at HelloKt.main(hello.kt:5)
        at HelloKt.main(hello.kt)

原因

Listにある数より多く「subList」で取得しようとしたため

対処法

範囲を超えないように「size」などを使用する

fun main() {

    var list = mutableListOf("aaa", "bbb", "ccc", "ddd", "eee")
    
    println(list.subList(0, list.size)) // [aaa, bbb, ccc, ddd, eee]

}