Groovy:Closure如何在sort()中工作 [英] Groovy: How Closure works in sort()

查看:87
本文介绍了Groovy:Closure如何在sort()中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个代码段:

I found a code segment like:

def l1 = ["hello","hi","hey"]    
l1.sort{new Random()}

我无法弄清楚Random类对象是usd排序/洗牌列表项目?如何使用Random类对象返回Comparable / Comparator对象来执行操作?

I could not figure out how a Random class object is being usd to sort/shuffle the list items? How Random class object is returning Comparable/Comparator object to perform operation?

在groovy文档中,我找到了以下语句:
使用给定的Closure对此Iterable进行排序以确定正确的顺序。
但在这里如何使用Random?

In the groovy doc, I found the statement: Sorts this Iterable using the given Closure to determine the correct ordering. But how Random is used here?

推荐答案

我怀疑这里的意图是随机值被用作每个条目的 Comparable (即使用 Iterable.sort(Closure closure) )。正在进行比较的是这些随机值,因此决定了排序顺序。因此,这导致了一个随机的排序顺序。

I suspect that the intent here is that a random value is used as the Comparable for each entry (i.e. using the single-argument closure variant of Iterable.sort(Closure closure)). It is these random values that are being compared, and thus dictating the sort order. Thus this leads to a randomised sort order.

然而,我不相信这会导致明确的行为。该文档没有定义:

However, I'm not convinced this leads to well-defined behaviour. The documentation does not define whether:


  1. 对于迭代器的每个元素,闭包都被精确计算一次。

  2. sort 应如何响应不一致的可比较值。

  1. The closure is evaluated precisely once for each element of the iterable.
  2. How sort should respond to inconsistent Comparable values.

如果#1不是真的,那么会产生不一致的值 - 目前还不清楚这是否会导致 sort 实现变得古怪事情。

If #1 is not true, then inconsistent values would get generated - it's unclear whether that would cause the sort implementation to do wacky things.

这篇关于Groovy:Closure如何在sort()中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆