Share Pastebin
Guest
Public paste!

Ryan Lie

By: a guest | Mar 21st, 2010 | Syntax: Java | Size: 1.83 KB | Hits: 54 | Expires: Never
Copy text to clipboard
  1. // the code probably needs more bounds checking
  2.  
  3. abstract class Slice extends AbstractList {
  4.   Object[][] table;
  5.   Slice(Object[][] table) {
  6.     this.table = table;
  7.   }
  8.   Object get(int row, int col) {
  9.     return this.table[row][col];
  10.   }
  11.   Object set(int row, int col, Object element) {
  12.     Object prev = this.table[row][col];
  13.     this.table[row][col] = element;
  14.     return prev;
  15.   }
  16. }
  17.  
  18. class RowSlice extends Slice {
  19.   private int row;
  20.   RowSlice(Object[][] table, int row) {
  21.     super(table);
  22.     this.row = row;
  23.   }
  24.  
  25.   int size() {
  26.     return this.table[row].length;
  27.   }
  28.  
  29.   Object get(int col) {
  30.     return super.get(row, col);
  31.   }
  32.   Object set(int col, Object element) {
  33.     return super.set(row, col, element);
  34.   }
  35. }
  36.  
  37. class ColumnSlice extends Slice {
  38.   private int col;
  39.   ColumnSlice(Object[][] table, int col) {
  40.     super(table);
  41.     this.col = col;
  42.   }
  43.   int size() {
  44.     return this.table.length;
  45.   }
  46.   Object get(int row) {
  47.     return super.get(row, col);
  48.   }
  49.   Object set(int row, Object element) {
  50.     return super.set(row, col, element);
  51.   }
  52. }
  53.  
  54. // note: we cannot use primitive type since int is not
  55. // a type of Object; i.e. boxed type only
  56. Integer[][] newTwoDim = new Integer[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
  57.  
  58. Slice rowOne = new RowSlice(newTwoDim, 1);
  59. Slice colOne = new ColumnSlice(newTwoDim, 1);
  60. Slice[] slices = new Slice[] {rowOne, colOne};
  61.  
  62. // note that because we inherits from AbstractList, there is
  63. // already a toString() implementation from AbstractList:
  64. print(rowOne); // [5, 6, 7, 8]
  65. print(colOne); // [2, 6, 10]
  66.  
  67. for (int i = 0; i < slices.length; i++) {
  68.   Slice flat = slices[i];
  69.   for (int j = 0; j < flat.size(); j++) {
  70.     int n = (Integer) flat.get(j);
  71.     flat.set(j, n + 1);
  72.   }
  73. }
  74.  
  75. print(rowOne); // [6, 8, 8, 9]
  76. print(colOne); // [3, 8, 11]