Skip to content

Instantly share code, notes, and snippets.

@matiangul
Created January 31, 2019 16:54
Show Gist options
  • Save matiangul/1eb529199c3f4e73615c00bf6a5f6f73 to your computer and use it in GitHub Desktop.
Save matiangul/1eb529199c3f4e73615c00bf6a5f6f73 to your computer and use it in GitHub Desktop.
Wzorzec projektowy adapter
/**
* @author Mateusz Angulski <mateusz@angulski.pl>.
*/
public class MapMatrix implements Matrix {
private final int size;
private final HashMap<String, Integer> matrix;
public MapMatrix(int size) {
this.size = size;
this.matrix = new HashMap<>(size * size);
}
public int get(int x, int y) {
this.assertBoundaries(x, y);
return this.matrix.getOrDefault(key(x, y), 0);
}
public void set(int x, int y, int value) {
this.assertBoundaries(x, y);
this.matrix.put(key(x, y), value);
}
private void assertBoundaries(int x, int y) {
if (x < 0 || x > size || y < 0 || y > size) {
throw new IllegalArgumentException(key(x, y));
}
}
public int size() {
return size;
}
private String key(int x, int y) {
return x + "," + y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment