我试图用从查询/findAllBy中创建的对象来填充一个地图列表...但最终我总是得到与循环中最后一个地图相同的地图列表。
我已经设定了断点并逐步执行该方法,发现1)从查询返回的数据是正确的,2)当我逐步执行循环时,数据被正确地插入到地图中,3)失败是在将地图插入列表中。我使用的所有将元素插入列表的方法(.add、.push、<<、list[(i)] = map等)都会覆盖列表中之前的所有元素。
请帮忙解决。我不知道为什么会出现这种情况。希望这对你们中的某个人来说是个容易的问题。
我已经设定了断点并逐步执行该方法,发现1)从查询返回的数据是正确的,2)当我逐步执行循环时,数据被正确地插入到地图中,3)失败是在将地图插入列表中。我使用的所有将元素插入列表的方法(.add、.push、<<、list[(i)] = map等)都会覆盖列表中之前的所有元素。
请帮忙解决。我不知道为什么会出现这种情况。希望这对你们中的某个人来说是个容易的问题。
def shiftRecords = Shift.findAllByUserAndStartTimeBetween( userInstance, startDate, endDate )
ArrayList allShifts = new ArrayList()
LinkedHashMap thisShift = new LinkedHashMap()
def size = shiftRecords.size()
for ( int i = 0; i < size; i++ ){
thisShift["id"] = shiftRecords[(i)].id
thisShift["user"] = shiftRecords[(i)].user
thisShift["startTime"] = shiftRecords[(i)].startTime
thisShift["posCode"] = shiftRecords[(i)].posCode
thisShift["deptCode"] = shiftRecords[(i)].deptCode
thisShift["billingIDX"] = shiftRecords[(i)].billingIDX
Position thisPos = Position.findByPositionCode( thisShift.posCode )
thisShift["posTitle"] = thisPos.shortTitle
thisShift["deptTitle"] = thisPos.departmentTitle
allShifts.add( (i), thisShift )
}
我希望将所有Shift的结果作为地图列表,并从Shift查询结果中选择数据。 我尝试使用shiftRecords.each和eachWithIndex。 问题出现在任何类型的循环中,当thisShift地图插入到allShifts中时。 它不仅插入了一个地图实例,而且用当前的thisShift地图替换了所有列表元素。
collect
的工作原理。我本可以花更多时间给你相同的答案(或类似的答案),而不是指出你的错误。但我更喜欢后者。 :) - dmahapatro