// the code probably needs more bounds checking
abstract class Slice extends AbstractList {
Object[][] table;
Slice(Object[][] table) {
this.table = table;
}
Object get(int row, int col) {
return this.table[row][col];
}
Object set(int row, int col, Object element) {
Object prev = this.table[row][col];
this.table[row][col] = element;
return prev;
}
}
class RowSlice extends Slice {
private int row;
RowSlice(Object[][] table, int row) {
super(table);
this.row = row;
}
int size() {
return this.table[row].length;
}
Object get(int col) {
return super.get(row, col);
}
Object set(int col, Object element) {
return super.set(row, col, element);
}
}
class ColumnSlice extends Slice {
private int col;
ColumnSlice(Object[][] table, int col) {
super(table);
this.col = col;
}
int size() {
return this.table.length;
}
Object get(int row) {
return super.get(row, col);
}
Object set(int row, Object element) {
return super.set(row, col, element);
}
}
// note: we cannot use primitive type since int is not
// a type of Object; i.e. boxed type only
Integer[][] newTwoDim = new Integer[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
Slice rowOne = new RowSlice(newTwoDim, 1);
Slice colOne = new ColumnSlice(newTwoDim, 1);
Slice[] slices = new Slice[] {rowOne, colOne};
// note that because we inherits from AbstractList, there is
// already a toString() implementation from AbstractList:
print(rowOne); // [5, 6, 7, 8]
print(colOne); // [2, 6, 10]
for (int i = 0; i < slices.length; i++) {
Slice flat = slices[i];
for (int j = 0; j < flat.size(); j++) {
int n = (Integer) flat.get(j);
flat.set(j, n + 1);
}
}
print(rowOne); // [6, 8, 8, 9]
print(colOne); // [3, 8, 11]