Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
int getCell(int x, int y){
	int index = calcIndex(x, y);
	return grid.get(index);
}

void setCell(int x, int y, int value){
	int index = calcIndex(x, y);
	return grid.set(index, value);
}

En ting må legges merke til: Du kan ikke bruke set og get på ArrayList med indexer høyere enn antallet elementer du har add-et. Vi blir derfor nødt til å initialisere ArrayList-en med null-er:

Code Block
for(int i = 0; i < (x_max * y_max); i++) {
	grid.add(null);
}

Satt sammen for vi kode som ser slik ut:

Code Block
class Grid {
	private ArrayList<Integer>List<Integer> grid = new ArrayList<Integer>();
	private int x_max;
	private int y_max;

	public Grid(int x_max, int y_max){
		this.x_max = x_max;
		this.y_max = y_max;

		for(int i = 0; i < (x_max * y_max); i++){
			grid.add(null);
		}
	}

	public int getCell(int x, int y){
		int index = calcIndex(x, y);
		return grid.get(index);
	}

	public void setCell(int x, int y, int value){
		int index = calcIndex(x, y);
		return grid.set(index);
	}

	private calcIndex(int x, int y){
		return y*x_max + x;
	}
}

...