所以,我有代码找到一个对象最接近0,0的空点。它落入无限循环,因为ArrayList就像一个指针列表。
private static voxel findEmptySpot(){
ArrayList<voxel> open = new ArrayList<voxel>();
ArrayList<voxel> closed = new ArrayList<voxel>();
String island = null;
open.add(new voxel(0,0));
do{
voxel pos = new voxel();
//Check for place closest to origin
int d = -1;
for(voxel test: closed){
SkyCraft.getInstance().getLogger().info("Closed: "+test.x+","+test.y);
}
for(voxel test: open){
int s = abs(test.x)+abs(test.y);
SkyCraft.getInstance().getLogger().info("Position "+test.x+", "+test.y+" distance "+s+" best "+d);
if(d==-1){
d = s;
pos.x = test.x;
pos.y = test.y;
}
if(s<d){
d = s;
pos.x = test.x;
pos.y = test.y;
}
}
SkyCraft.getInstance().getLogger().info("Closest found; testing.");
Island i = SkyCraft.db().getIsland(pos.x+";"+pos.y);
if(i.owner!=null){
if(i.owner.equals("")){
return pos;
}else{
voxel x1 = new voxel(pos.x+1, pos.y);
voxel x2 = new voxel(pos.x-1, pos.y);
voxel y1 = new voxel(pos.x, pos.y+1);
voxel y2 = new voxel(pos.x, pos.y-1);
if(!closed.contains(new voxel(pos.x+1, pos.y))){
if(!open.contains(new voxel(pos.x+1, pos.y))){
open.add(new voxel(pos.x+1, pos.y));
}
}
if(!closed.contains(new voxel(pos.x-1, pos.y))){
if(!open.contains(new voxel(pos.x-1, pos.y))){
open.add(new voxel(pos.x-1, pos.y));
}
}
if(!closed.contains(new voxel(pos.x, pos.y+1))){
if(!open.contains(new voxel(pos.x, pos.y+1))){
open.add(new voxel(pos.x, pos.y+1));
}
}
if(!closed.contains(new voxel(pos.x, pos.y-1))){
if(!open.contains(new voxel(pos.x, pos.y-1))){
open.add(new voxel(pos.x, pos.y-1));
}
}
open.remove(pos);
closed.add(pos);
}
}else{
return pos;
}
}while(true);
}
当列表的值关闭打印时,这些值都等于当时变量pos的值。它就像是来自C ++的指针列表。如何让ArrayList实际包含对象本身,而不是对象的引用?
答案 0 :(得分:-1)
我刚使用了&#34; new&#34;函数创建变量的实例,然后将ant分配给ArrayList。谢谢@William Price的帮助。