【发布时间】:2013-12-04 21:29:41
【问题描述】:
我是 java 中的菜鸟,我似乎无法弄清楚每次我向 ArrayList 添加新项目时,以前的项目如何与新项目完全相同。我从这里的帖子中学到了同样的问题,但我似乎仍然无法弄清楚真正的问题是什么。我已经在这里待了一个星期了。希望有人能提供帮助。
这是我的代码:
private void generation(String numberOfCase,int i, int j){
switch(numberOfCase){
case "N":
int tempN = 0;
if(i == 1)
tempN = 0;
if(i == 2)
tempN = 1;
forGenerating[i][j] = current[tempN][j];
forGenerating[tempN][j] = 0;
State tempNo = new State(forGenerating,current,1,howFar);
adding(tempNo);
//adding(forGenerating,current,1,howFar);
forGenerating[tempN][j] = forGenerating[i][j];
forGenerating[i][j] = 0;
break;
case "E":
int tempE = j+1;
forGenerating[i][j] = current[i][tempE];
forGenerating[i][tempE] = 0;
State tempEa = new State(forGenerating,current,1,howFar);
adding(tempEa);
//adding(forGenerating,current,1,howFar);
forGenerating[i][tempE] = forGenerating[i][j];
forGenerating[i][j] = 0;
break;
case "S":
int tempS = 0;
if(i == 0)
tempS = 1;
if(i == 1)
tempS = 2;
forGenerating[i][j] = current[tempS][j];
forGenerating[tempS][j] = 0;
State tempSo = new State(forGenerating,current,1,howFar);
adding(tempSo);
//adding(forGenerating,current,1,howFar);
forGenerating[tempS][j] = forGenerating[i][j];
forGenerating[i][j] = 0;
break;
case "W":
int tempW = j-1;
forGenerating[i][j] = current[i][tempW];
forGenerating[i][tempW] = 0;
State tempWe = new State(forGenerating,current,1,howFar);
adding(tempWe);
//adding(forGenerating,current,1,howFar);
forGenerating[i][tempW] = forGenerating[i][j];
forGenerating[i][j] = 0;
break;
}
}
private void adding(State temp){
State t = new State(temp);
if(closedList.equals(temp) == false){
forChecking.add(t);
iterator+=1;
}
}
我创建了我为州创建的类的 ArrayList。
编辑。这是班级状态。有两个构造函数,因为我已经编辑了这个代码一个星期,并做了我从网上读到的所有可能的解决方案。
导入 java.util.Arrays; 导入 java.util.Random;
公共类状态{
int[][] arr = new int[3][3];
int[][] parent = new int[3][3];
int g=0,f=0,h=0;
public State(int[][] arr, int[][] parent, int g, int h){
this.arr = Arrays.copyOf(arr, arr.length);
this.parent = Arrays.copyOf(parent, parent.length);
this.g = g;
this.h = h;
solveF();
}
public State(State temp){
this.arr = Arrays.copyOf(temp.arr, temp.arr.length);
this.parent = Arrays.copyOf(temp.parent, temp.parent.length);
this.g = temp.g;
this.h = temp.h;
solveF();
}
private void solveF(){
f = g+h;
}
}
【问题讨论】:
-
ArrayList在哪里? -
List
forChecking = new ArrayList ();在这里,我是这样做的 -
您的代码应该没有问题。我唯一看到的是,当您执行新状态(临时)时,您必须修改您的类状态的静态成员,这就是为什么您的所有实例都同时被修改(或者至少看起来是)。你能展示你的班级状态吗?
-
我认为这是我的错误。而且我真的不知道如何不修改数组列表。我尝试了在有关此问题的相关主题上学到的不同建议。谢谢