fun <T> Array<out T>.slice(indices: IntRange): List<T> fun <T> List<T>.slice(indices: IntRange): List<T> fun <T> Array<T>.sliceArray(indices: IntRange): Array<T>
예시)
val array = intArrayOf(0, 1, 2, 3, 4, 5)
val slicedList = array.slice(2..5)
val slicedArray = array.sliceArray(IntRange(2, 5))
println(array.contentToString()) // [0, 1, 2, 3, 4, 5]
println(slicedList) // [2, 3, 4, 5]
println(slicedArray.contentToString()) // [2, 3, 4, 5]
fun <T> Array<T>.copyOfRange( fromIndex: Int, toIndex: Int ): Array<T>
fromIndex
~ toIndex - 1
구간으로 배열을 자름예시)
val array = intArrayOf(0, 1, 2, 3, 4, 5)
val copiedArray = array.copyOfRange(2, 5)
println(copiedArray.contentToString()) // [2, 3, 4]
abstract fun subList(fromIndex: Int, toIndex: Int): List<E>
fromIndex
~ toIndex - 1
구간으로 리스트를 자름예시)
val list = mutableListOf(0, 1, 2, 3, 4, 5)
val subList = list.subList(2, 5)
println(list) // [0, 1, 2, 3, 4, 5]
println(subList) // [2, 3, 4]
slice()는 원본 List를 잘라 새로운 List를 만들어 리턴하지만, subList()는 원본 List를 원하는 구간만큼만 잘라서 보여준다.
예시)
val list = mutableListOf(0, 1, 2, 3, 4, 5)
val slicedList = list.slice(2..5)
val subList = list.subList(2, 6)
println(slicedList) // [2, 3, 4, 5]
println(subList) // [2, 3, 4, 5]
list[2] = 1 // 원본리스트에 변경 생김
println(slicedList) // [2, 3, 4, 5]
println(subList) // [1, 3, 4, 5]