如何循环访问对象?

时间:2019-06-16 10:31:42

标签: java

我正在尝试将对象“下一个”的位置值移交给下一个“下一个”对象。可以将此代码编写为循环并按n缩放吗?


next.next.next.next.pos.y = next.next.next.pos.y;
next.next.next.next.pos.x = next.next.next.pos.x;
next.next.next.pos.y = next.next.pos.y;
next.next.next.pos.x = next.next.pos.x;
next.next.pos.y = next.pos.y;
next.next.pos.x = next.pos.x;
next.pos.x = pos.x;
next.pos.y = pos.y;

1 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

while(obj.next != null) {
  obj.next.pos.x = obj.pos.x;
  obj.next.pos.y = obj.pos.y;
  obj = obj.next;
}

以后编辑:

对不起,我误解了你的问题。

然后可以使用列表来解决此问题。这不是最高效的方法,但我会努力的。

List<Obj> objs = new ArrayList<>();

objs.add(obj);

// Add everything to a list
while(obj.next != null) {
    objs.add(obj.next);
    obj = obj.next;
}

// Walk the list in the reverse order
for(i = objs.size() - 1; i > 1 ; i--) {
  objs[i].pos.x = objs[i - 1].pos.x;
  objs[i].pos.y = objs[i - 1].pos.y;
}
相关问题