Java 或 Kotlin - 创建尽可能多的子列表

Dav*_*nan 3 java list kotlin

在 Java 或 Kotlin 中,如何创建尽可能多的子列表?如果范围大于列表的大小,它应该只忽略超出范围的部分范围。

我目前有(科特林):

val list: List = arrayListOf(1, 2, 3, 4)
list.subList(0, 3) // -> [1, 2, 3]
list.subList(0, 5) // -> IndexOutOfBoundsException
list.subList(0, 200) // -> IndexOutOfBoundsException
list.clear()
list.subList(0, 3) // -> IndexOutOfBoundsException
Run Code Online (Sandbox Code Playgroud)

我想要(科特林):

val list: List = arrayListOf(1, 2, 3, 4)
list.subList(0, 3) // -> [1, 2, 3]
list.subList(0, 5) // -> [1, 2, 3, 4]
list.subList(0, 200) // -> [1, 2, 3, 4]
list.clear()
list.subList(0, 3) // -> []
Run Code Online (Sandbox Code Playgroud)

Fel*_*nde 12

在 Kotlin 中你可以做

val list = mutableListOf(1, 2, 3, 4)
list.take(3) // -> [1, 2, 3]
list.take(5) // -> [1, 2, 3, 4]
list.take(200) // -> [1, 2, 3, 4]
list.clear()
list.take(3) // -> []
Run Code Online (Sandbox Code Playgroud)

take如果您愿意,您可以检查实施情况。


Tod*_*odd 8

您可以编写一个扩展List<T>来为您执行此逻辑:

fun <T> List<T>.safeSubList(fromIndex: Int, toIndex: Int): List<T> =
    this.subList(fromIndex, toIndex.coerceAtMost(this.size))
Run Code Online (Sandbox Code Playgroud)

这用于coerceAtMost限制最高值。

并称之为:

val list = arrayListOf(1, 2, 3, 4)
println(list.safeSubList(0, 200)) // -> [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

或者正如@gidds 所建议的那样,我们可以使这更安全:

fun <T> List<T>.safeSubList(fromIndex: Int, toIndex: Int): List<T> = 
    this.subList(fromIndex.coerceAtLeast(0), toIndex.coerceAtMost(this.size))
Run Code Online (Sandbox Code Playgroud)

此版本防止在两端指定超出范围的数字。如果你传入的数字是从 > 到,它会抛出一个IllegalArgumentExceptionfrom subList

  • 这也是我的做法。您还可以通过限制 fromValue 使其更加安全;并限制它们为 &gt;= 0 以及 &lt;= `size`;也可能通过确保 `fromIndex` &lt;= `toIndex` 。(尽管可以说这可能太安全了……) (2认同)