Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List Groovy:使用范围运算符创建列表_List_Exception_Groovy_Range - Fatal编程技术网

List Groovy:使用范围运算符创建列表

List Groovy:使用范围运算符创建列表,list,exception,groovy,range,List,Exception,Groovy,Range,我试图从int列表中选择一个随机元素,列表元素是用range操作符创建的: def date_range = 1..28 assert ('a'..'d').collect() == ['a','b','c','d'] // So this is instanceof List assert ('a'..'d') == ['a','b','c','d'] // So this is instanceof List def x1 = (1..28).collect().sort{new Rando

我试图从int列表中选择一个随机元素,列表元素是用range操作符创建的:

def date_range = 1..28
assert ('a'..'d').collect() == ['a','b','c','d'] // So this is instanceof List
assert ('a'..'d') == ['a','b','c','d'] // So this is instanceof List
def x1 = (1..28).collect().sort{new Random()}?.take(1)[0] // works
def x2 = date_range.collect().sort{new Random()}?.take(1)[0] // works
def x3 = date_range[0..27].sort{new Random()}?.take(1)[0] //works
def x4 = date_range.sort{new Random()}?.take(1)[0] // does not works
x4屈服于以下异常

Caught: java.lang.UnsupportedOperationException
java.lang.UnsupportedOperationException
    at listManipulation.run(listManipulation.groovy:21)
我在x4上的错误是什么

更新:


我的困惑是:如果我将日期范围定义为
def date\u range=1..28
,并选中类似的:
assert date\u range instanceof List
,那么它就会通过。为什么要再次将其转换为列表?

date\u范围
的类型为
IntRange
。不确定为什么
范围上不支持
排序
。但是
toSorted
可以用来实现同样的效果

您应该能够使用以下命令调用它:

def date_range = 1..28 
def x4 = date_range.toSorted {new Random()}?.take(1)[0]​
println x4
另外,将范围转换为
排序
之前的
数组
列表
(这是
x3
的情况),如下所示:

println date_range.toList().sort {new Random()}?.take(1)[0]
println date_range.toArray().sort {new Random()}?.take(1)[0]
编辑:基于OP的评论


date\u范围
是不可变的列表

在所有x1、x2、x3中,您只创建一个集合/列表(在不可变列表上),该集合/列表变为可变的,然后可以进行排序。同上

排序
不允许在
不可变列表上进行排序

下面的工作

def mutableList = ['Groovy', 'Java', 'JRuby']
mutableList.sort()
但是,一旦列表是不可变的,它现在就允许和结果
UnsupportedOperation
异常

def immutableList = ['Groovy', 'Java', 'JRuby'].asImmutable()
immutableList.sort()

希望现在一切都清楚了。

并非每个列表都支持
排序。对于ex,非常感谢您提供的宝贵信息和更新!这意味着范围运算符(..)创建了不可变列表。