Data Structures, Algorithms, & Applications in Java
Chapter 8, Exercise 43
The code to make a clone is given below. The code clones each matrix term
by copying the data members of the matrix term. An iterator is used to
retrieve the matrix terms from the ExtendedArrayList
they are stored in.
public class SparseMatrixAsExtendedArrayListWithClone
extends SparseMatrixAsExtendedArrayList
implements CloneableObject
{
// constructors
public SparseMatrixAsExtendedArrayListWithClone
(int theRows, int theColumns,
int estimatedMaxSize, Object theZero)
{super(theRows, theColumns, estimatedMaxSize, theZero);}
/** use a default estimated maximum size of 1 */
public SparseMatrixAsExtendedArrayListWithClone
(int theRows, int theColumns,
Object theZero)
{this(theRows, theColumns, 1, theZero);}
/** defaults are rows = cols = estimatedMaxSize = 1 */
public SparseMatrixAsExtendedArrayListWithClone(Object theZero)
{this(1, 1, 1, theZero);}
/** read in a sparse matrix into this from the given input stream */
public void read(Object theZero, MyInputStream stream)
{
SparseMatrixAsExtendedArrayList x = input(theZero, stream);
// transfer to SparseMatrixAsExtendedArrayListWithClone
rows = x.rows;
cols = x.cols;
zero = x.zero;
terms = x.terms;
}
/** return a clone of this */
public Object clone()
{
// define the clone w
SparseMatrixAsExtendedArrayListWithClone w =
new SparseMatrixAsExtendedArrayListWithClone
(rows, cols, terms.size(), zero);
// set the matrix elements by using a ExtendedArrayList enumerator
Iterator it = terms.iterator();
int cw = 0; // cursor into w
while (it.hasNext())
{
MatrixTerm nextTerm = (MatrixTerm) it.next();
MatrixTerm clonedTerm = new MatrixTerm(nextTerm.row, nextTerm.col,
((CloneableObject) nextTerm.value).clone());
w.terms.add(cw++, clonedTerm);
}
return w;
}
}