gpt4 book ai didi

groovy - Groovy 中的安全范围运算符?

转载 作者:行者123 更新时间:2023-12-04 23:55:12 30 4
gpt4 key购买 nike

Groovy 是否有安全范围运算符?

例如,如果我有,

[1,2,3][0..10]

Groovy 会抛出一个 java.lang.IndexOutOfBoundsException:
有没有索引安全的方式来访问这个范围?或者我是否总是必须在运行范围之前检查集合大小?

最佳答案

您可以使用 take(n) ,它允许您使用特定数量的项目,如果集合中的项目太少,则不会出错:

def input = [1,2,3]
def result = input.take(10)
assert result == [1,2,3]

input = [1,2,3,4,5]
result = input.take(4)
assert result == [1,2,3,4]

如果需要从偏移量开始,可以使用 drop(n) , 这样做 不是 修改原始集合:
def input = [1,2,3,4,5]
def result = input.drop(2).take(2)
assert result == [3,4]

这些对于集合的大小都是安全的。如果上一个示例中的列表太小,则集合中可能只有一个或零个项目。

关于groovy - Groovy 中的安全范围运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17459507/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com