Comp 271 lab 2 - The Matrix
Goals
- Building a 2-D structure out of ArrayLists
- non-linear iterators
Overview
You are to create a class Matrix<E>, where
E is the component type. A Matrix is essentially an m×n array; that is,
m rows and n columns. A bluej starter file is here. In the starter file I implement:
- Matrix(int rows, int cols) (constructor)
- int height() and int width()
- E get(int i, int j): usual get() operation for row i, col j. Precondition: 0<=i<height(), 0<=j<width().
- E set(int i, int j, E value): set operation
- rowIterator(): an iterator that traverses the matrix in row-major order
- print(int fieldwidth): prints the matrix while attempting to line things up neatly in columns of specified width
Here are the operations you are to implement:
1. void addRow(): adds one more row to the matrix; the data values of the new row are initialized to null. Note that, unlike ArrayList.add(), you do not add any data values when you add a row; you fill it in with null. It is perhaps simplest to create the new row ArrayList<E> newRow, fill it with the correct number of null entries, and then add it to rows. Don't forget to increment rowcount.
2. void addColumn(): Like
addRow(), except a new column is added. Note that this means you will
add an extra null to each existing row of the matrix, but you will not be creating any new ArrayList objects.
3. ArrayList<E> rowList(): Returns an ArrayList<E> of all the elements of the matrix, row by row. That is, if the matrix is
apple
|
artichoke
|
allspice
|
berry
|
bean
|
basil
|
cherry
|
cauliflower
|
cinnamon
|
then rowList() would return the list <apple, artichoke, allspice, berry, bean, basil, cherry, cauliflower, cinnamon>
4. Iterator<E> colIterator():
returns an iterator that generates the elements by column (that is,
apple, berry, cherry, artichoke, ...). Note that rowIterator() returns
the elements by row: apple, artichoke, allspice, berry, .... Note also
that the colIterator() method itself is done (and is trivial); what you
have to do is finish the private class MyColIterator.
5. Methods in class MatrixTester that test
each of your four methods above. It suffices, for now, to test by doing
the desired action and then printing the result. For #3 and #4, print
the resultant ArrayList or the output that would be created by the
iterator. For #1 and #2, add the row/column, fill it in, and then print it. I've started a method addtest() that adds a row; you can use the same method or a different one to add a column as well.
Added September 15: my MatrixTester.java file, so if you're still working on this you can focus on the implementation in Matrix, and not the testing.
To submit your project, create a zipfile and email it to me at pld@cs.luc.edu.