加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy List参数问题:=不起作用但.add()起作用

发布时间:2020-12-14 16:20:36 所属栏目:大数据 来源:网络整理
导读:public updateList(lst) { lst += "a"}List lst = []updateList(lst)println(lst) 这会打印一个空列表.然而; public updateList(lst) { lst.add("a")}List lst = []updateList(lst)println(lst) ,将根据需要打
public updateList(lst) {
  lst += "a"
}

List lst = []
updateList(lst)
println(lst)

这会打印一个空列表.然而;

public updateList(lst) {
  lst.add("a")
}

List lst = []
updateList(lst)
println(lst)

,将根据需要打印“a”.

我总是假设=与.add()相同,但显然不是.我假设=正在创建一个新的List,而.add()只更新了现有的List?

解决方法

第一个方法在lst变量上调用plus

我们可以看到from the documentation这将:

Create a collection as a union of a
Collection and an Object.

因此将返回一个新的集合,原始的lst(在此方法的范围之外)将保持不变. (显然,在这个方法的范围内,lst将是一个包含一个元素的新列表)

这可以通过打印出updateList方法的结果来看出:

public updateList(lst) {
  lst += "a"  // calls plus,creates a new list,and returns this new list.
              // lst (outside the context of this method) is unmodified
}

List lst = []
println( updateList(lst) )

如果您拨打add,则拨打standard java add method.

public updateList(lst) {
  lst.add "a"
}

所以原来的lst被修改了

添加的替代方法是使用leftShift运算符:

public updateList(lst) {
  lst << "a"
}

幕后添加哪些调用:(来自Groovy主干源的代码)

public static <T> Collection<T> leftShift(Collection<T> self,T value) {
    self.add(value);
    return self;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读