1 /**
2 * A rectangular array of objects
3 *
4 */
5 public class RectangularArrayTS <T>
6 {
7 private int columns, rows;
8 private T[] data; // matches T
specified in the constructor
9
10
11 /**
12 * Explicit Value Constructor
13 *
14 * @param
rows The number of rows
15 * @param columbs The number of columns
16 */
17 public RectangularArrayTS
(int rows, int columns)
18 {
19 this.columns = columns;
20 this.rows = rows;
21 data = (T[]) new
Object [rows * columns];
22 // we still have an array of objects
but we are
23 // casting it to an array of T
24 }// end RectangularArray
constructor
25
26
27 /**
28 * Returns the number of columns in this RectangularArray
29 *
30 * @return
The number of columns
31 */
32 public int columns()
33 {
34 return columns;
35 } // end columns
36
37 /**
38 * Get the element at a particular row and
column
39 *
40 * @param
row The row index
41 * @param
column The column index
42 * @return The Object at the given row and column
43 */
44 public T getElementAt(int row, int column)
45 throws IndexOutOfBoundsException
46 {
47 T myObject;
48 int i;
49 i = index(row,
column);
50 myObject = data[i];
51 return myObject;
52 }// end getElementAt
53
54 /**
55 * This implementation uses an ordinary
array as the underlying
56 * data structure. This converts from VALID row and column
57 * indexes to an index into the underlying
data structure.
58 *
59 * @param
row The row index
60 * @param
column The column index
61 * @return The corresponding index in the data
array
62 */
63 private int index(int row, int column)
64 // throws IndexOutOfBoundsException
65 {
66 int i;
67 i = row*columns + column;
68 if (row > rows || column > this.columns || i > data.length)
69 throw new IndexOutOfBoundsException
70 (" row: " + row + " column:
" + column);
71 // parameter is message
72 else
73 return i;
74 }// end index
75
76 /**
77 * Returns the number of rows in this RectangularArray
78 *
79 * @return
The number of rows
80 */
81 public int rows()
82 {
83 return rows;
84 } // end rows
85
86
87 /**
88 * Set the element at a particular row and
column
89 *
90 * @param
row The row index
91 * @param
column The column index
92 * @param o The Object to put in the array
93 */
94 public void setElementAt(int row, int column, T
o)
95 throws IndexOutOfBoundsException
96 {
97 int location;
98 location = index(row,column);
99 data[location] = o; // terrible variable name
100
101 } // end setElementAt
102 }// end class
103