在我的節目,我有一個名爲Cell類,像這樣定義的:我創建equals()和hashCode()是沒有做任何事情
public class Cell {
private int x;
private int y;
public Cell (int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals (Object o) {
boolean result = false;
if (o instanceof Cell) {
Cell other = (Cell) o;
result = (this.x == other.x && this.y == other.y)
}
return result;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
我有一個網格類,像這樣(很多方法切出名和變量名簡化):
public class Grid {
private Set<Cell> cellArray;
public Grid() {
cellArray = new HashSet<Cell>();
}
public Set<Cell> getCellArray() {
return cellArray;
}
public void addCellArray(Cell cell) {
cellArray.add(cell)
}
}
以我的代碼主體,我走在網格對象,像這樣:
public class Controller {
private Grid grid;
public Controller (Grid grid) (
this.grid = grid;
然後,I H AVE系列迴路看起來像這樣:
private set<Cell> cellArray = grid.getCellArray();
boolean endLoop = false;
do {
x = randomGenerator.nextInt(10);
y = randomGenerator.nextInt(10);
for (int i = 0; i < length; i++) {
if (cellArray.contains(new Cell(x, y+i))) {
continue;
}
}
for (int j = 0; j < length; j++) {
cellArray.add(new Cell(x, y+i));
}
endLoop = true;
} while(!endLoop);
我知道這是一個非常混亂,有太多的實例事情(如果任何人有三分球,使之清潔,可隨時指出來)但是,主要問題是第一個for循環意味着檢查cellArray是否包含項目 - 它似乎沒有這樣做。
沒有錯誤消息,沒有空指針或類似的東西。我試着調試它,看到它比較兩個具有相同x和y值的單元格,而沒有繼續執行continue語句以再次啓動do while循環。
我假設這是因爲即使它們具有相同的值,它們是不同的'對象',因此不會相等。
我該如何解決這個問題,如果它們的值相同,讓它們相互等價?
'private set cellArray = Grid.getCellArray();在'Grid'類中''''''getCellArray'不是靜態的。這會顯示編譯時錯誤。 –
2013-05-01 10:16:48
|
爲什麼它需要是靜態的?我沒有收到任何編譯時錯誤。 – 2013-05-01 10:17:41
如何在不創建實例的情況下調用類的非靜態方法? – 2013-05-01 10:18:24