【问题标题】:Groovy list in a map not showing a loop count properly地图中的 Groovy 列表未正确显示循环计数
【发布时间】:2020-06-11 16:54:50
【问题描述】:

我在 Groovy 中有这段代码;

def execution = []
def executor =[:]
for(loopcount=1;loopcount<4;loopcount++){
    executor.executor = 'jmeter'
    executor.scenario = 'scenario' + loopcount
    println executor.scenario
    executor.concurrency = 2
    execution.add(executor)
}
execution.each{
    println executor.scenario
}

它是三张地图的列表,除了场景后缀增量之外,所有地图都相同。我期待;

scenario1
scenario2
scenario3
scenario1
scenario2
scenario3

但我明白了;

scenario1
scenario2
scenario3
scenario3
scenario3
scenario3

它肯定会在列表中添加三个不同的映射,因为 .each 命令返回三个值。它们在 executor.scenario 中绝对是不同的值,因为循环中的 println 给出了正确的 '1, 2, 3' 计数。但是为什么它们不在列表中保留为不同的值呢?

我也尝试过 execution.push(executor) ,但结果相同。就上下文而言,这个 yaml 是我最终的目标;

---
execution:
- executor: "jmeter"
  scenario: "scenario1"
  concurrency: 2
- executor: "jmeter"
  scenario: "scenario2"
  concurrency: 2
- executor: "jmeter"
  scenario: "scenario3"
  concurrency: 2

除了场景计数之外,其余部分都可以正常工作。

【问题讨论】:

  • 这里有'byval'和'byref'的概念吗?如果是这样,我是否需要对 execution.add(executor) 做一些事情以使其获取值而不是引用?
  • 只需将def executor =[:] 声明移动到for 循环内

标签: list groovy hashmap


【解决方案1】:

问题:

def execution = []
def executor =[:]
for(loopcount=1;loopcount<4;loopcount++){
    execution.add(executor) // <<-- this line adds the same variable to the list 4 times
}

解决这个问题 - 在 for 循环中声明 executor

def execution = []
for(loopcount=1;loopcount<4;loopcount++){
    def executor =[:]       // <<-- creates a new object in a loop
    execution.add(executor) // <<-- adds new object to a list
}

可能为了更清楚,让我指定 [][:] 的含义:

def execution = new ArrayList()
for(loopcount=1;loopcount<4;loopcount++){
    def executor = new LinkedHashMap()
    execution.add(executor)
}

但是你可以在循环之前声明变量,但你必须在循环内为它分配一个新对象

def execution = []
def executor
for(loopcount=1;loopcount<4;loopcount++){
    executor = [:]
    execution.add(executor)times
}

【讨论】:

  • 不错的简单修复,谢谢!我不认为我能够在循环中进行另一个声明,我认为它只是告诉我在第二个循环中离开。我实际上是在寻找一种“删除”执行程序的方法,以便我可以重用它,但当然 Java(以及扩展的 Groovy)没有任何东西可以删除对象。
猜你喜欢
  • 2019-09-10
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
相关资源
最近更新 更多