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

Java或Kotlin-创建尽可能多的子列表,java,list,kotlin,Java,List,Kotlin,在Java或Kotlin中,如何创建尽可能多的子列表?如果范围大于列表的大小,则应忽略范围中超出范围的部分 我目前有(Kotlin): 我想(科特林): Arraylist是通过数组实现的。所以你不可能得到比实际金额小的子列表 arrayListOf(1, 2, 3, 4) 这意味着,只能得到0-4之间的范围 您可以尝试此操作以避免IndexOutOfBoundsException int maxRange = yourGivenMaxRange; if(maxRange >

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

我目前有(Kotlin):

我想(科特林):


Arraylist是通过数组实现的。所以你不可能得到比实际金额小的子列表

arrayListOf(1, 2, 3, 4)
这意味着,只能得到0-4之间的范围


您可以尝试此操作以避免IndexOutOfBoundsException

int maxRange = yourGivenMaxRange;

    if(maxRange > list.size()){
        maxRange = list.size();
    }

list.subList(0, maxRange) // -> [1, 2, 3]
list.subList(0, maxRange) // -> [1, 2, 3, 4]
list.subList(0, maxRange) // -> [1, 2, 3, 4]
list.clear()
list.subList(0, maxRange) // -> []

您可以在
列表
上编写一个扩展来为您执行此逻辑:

fun <T> List<T>.safeSubList(fromIndex: Int, toIndex: Int): List<T> =
    this.subList(fromIndex, toIndex.coerceAtMost(this.size))
或者正如@gidds所建议的,我们可以让这更安全:

fun <T> List<T>.safeSubList(fromIndex: Int, toIndex: Int): List<T> = 
    this.subList(fromIndex.coerceAtLeast(0), toIndex.coerceAtMost(this.size))
fun List.safeSubList(从index:Int到index:Int):List=
this.subList(从index.convereatmest(0)到index.convereatmest(this.size))
此版本防止在两端指定超出范围的数字。如果您传入的数字是from>到,它将在Kotlin中抛出一个
IllegalArgumentException
from
子列表

,您可以这样做

val list=mutableListOf(1,2,3,4)
列表。取(3)/->[1,2,3]
列表。取(5)/->[1,2,3,4]
列表。取(200)/->[1,2,3,4]
list.clear()
列表。取(3)/->[]

如果愿意,您可以检查
take
的实现。

See OP说他知道这一点,但他需要一种不同的行为。这也是我的方法。您还可以通过限制fromValue使其更加安全;通过将它们限制为>=0以及
fun <T> List<T>.safeSubList(fromIndex: Int, toIndex: Int): List<T> =
    this.subList(fromIndex, toIndex.coerceAtMost(this.size))
val list = arrayListOf(1, 2, 3, 4)
println(list.safeSubList(0, 200)) // -> [1, 2, 3, 4]
fun <T> List<T>.safeSubList(fromIndex: Int, toIndex: Int): List<T> = 
    this.subList(fromIndex.coerceAtLeast(0), toIndex.coerceAtMost(this.size))