我遇到了以下代码片段的问题,其中创建了元素数组并用随后创建的项填充。输出显示特定元素是引擎类的不同实例(按预期方式),但属性值中表示为(属性 EngineInput )取自最后创建的元素并复制(引用?)到前面的元素。 我在网上进行了研究,发现这种行为的主要原因是:
或
有人知道为什么 in 属性被复制到数组tasks
的所有元素?
段
List<Engine> tasks = new ArrayList<>();
for (int i = 0; i < segs.size(); i++) {
Segment s = new Segment(segs.get(i));
EngineInput in = new EngineInput(new Store(store), s);
Engine ce = new Engine(in);
tasks.add(i, ce);
log.debug("-------");
// After completing the i-th step we print a reference of each element of the
//"tasks" array together with a reference of its property "in"
for (int j = 0; j < i; j++) {
log.debug("\t\tj = " + j + " CE : " + tasks.get(j) +
" --> IN : " + tasks.get(j).getIn() );
}
}
输出
请注意,数组的所有元素都填充了引用foo.calcs.EngineInput@
(为什么????)
[DEBUG] 2016-10-17 23:32:11.706 [main] Optimizer - j = 0 CE : foo.calcs.Engine@34414ffc --> IN : foo.calcs.EngineInput@1903b5d [DEBUG] 2016-10-17 23:32:11.792 [main] Optimizer - ------- [DEBUG] 2016-10-17 23:32:11.793 [main] Optimizer - j = 0 CE : foo.calcs.Engine@34414ffc --> IN : foo.calcs.EngineInput@4041739c [DEBUG] 2016-10-17 23:32:11.793 [main] Optimizer - j = 1 CE : foo.calcs.Engine@5cff6b74 --> IN : foo.calcs.EngineInput@4041739c [DEBUG] 2016-10-17 23:32:11.879 [main] Optimizer - ------- [DEBUG] 2016-10-17 23:32:11.880 [main] Optimizer - j = 0 CE : foo.calcs.Engine@34414ffc --> IN : foo.calcs.EngineInput@627ff1b8 [DEBUG] 2016-10-17 23:32:11.881 [main] Optimizer - j = 1 CE : foo.calcs.Engine@5cff6b74 --> IN : foo.calcs.EngineInput@627ff1b8 [DEBUG] 2016-10-17 23:32:11.881 [main] Optimizer - j = 2 CE : foo.calcs.Engine@62b57479 --> IN : foo.calcs.EngineInput@627ff1b8 [DEBUG] 2016-10-17 23:32:11.981 [main] Optimizer - ------- [DEBUG] 2016-10-17 23:32:11.982 [main] Optimizer - j = 0 CE : foo.calcs.Engine@34414ffc --> IN : foo.calcs.EngineInput@29a33620 [DEBUG] 2016-10-17 23:32:11.982 [main] Optimizer - j = 1 CE : foo.calcs.Engine@5cff6b74 --> IN : foo.calcs.EngineInput@29a33620 [DEBUG] 2016-10-17 23:32:11.982 [main] Optimizer - j = 2 CE : foo.calcs.Engine@62b57479 --> IN : foo.calcs.EngineInput@29a33620 [DEBUG] 2016-10-17 23:32:11.982 [main] Optimizer - j = 3 CE : foo.calcs.Engine@ea04cab --> IN : foo.calcs.EngineInput@29a33620 [DEBUG] 2016-10-17 23:32:12.082 [main] Optimizer - -------