gpt4 book ai didi

Groovy 列表参数问题 : += does not work but . add()

转载 作者:行者123 更新时间:2023-12-01 10:13:34 25 4
gpt4 key购买 nike

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() 相同,但显然不是。我假设 += 正在创建一个新列表,而 .add() 只更新了现有列表?

最佳答案

第一个方法在 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

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

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

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

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

关于Groovy 列表参数问题 : += does not work but . add(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3342514/

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