-1
所以,我有代码找到一个对象最接近0,0的空白点。它陷入了一个无限循环,因为ArrayList的行为像一个指针列表。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实际包含对象本身,而不是对象的引用?
Java集合都是通过引用。 –
因此,如果每次向阵列列表添加对象时都使用“新”来引用新对象,那么列表中的每个引用都将具有唯一对象,是否正确? – Mad3ngineer
是的,每个单独的'新'实例将是一个单独的,可以添加到列表中的唯一引用。你的代码也使用'List.contains()'[用对象相等的方式定义](http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains %28java.lang.Object%29),它不一定与参考质量相同,具体取决于要比较的对象的类型以及如何实现“equals”方法。也看看http://stackoverflow.com/questions/2642589/how-does-a-arraylists-contains-method-evaluate-objects –