/**
*
*/
package student_classes;
/**
*
Simulates the old-fashioned "vector" class, which behaved a lot like an array
* that could shrink and grow.
* Note: one might think of this class definition as an introduction to the ArrayList
* data-type, which will be introduced within the next week or so.
*
* @author Tom R
*
*/
public class Vector {
private Object[] vector; // note this data type ...
private static final int DEFAULT_SIZE=16; // initial size
private static final int QUANTA=8; // how many buckets to add ...
/* ask yourself: why is this next instance variables necessary?
* How will it be used?
*/
private int effective_index = 0;
// ctor(s):
public Vector() {
// default ctor, makes an array of the default size.
this.vector = new Object[ DEFAULT_SIZE ];
}
// public interface:
public void add( Object element ) {
if( this.effective_index < this.vector.length ) {
this.vector[ this.effective_index++ ] = element;
return;
}
this.growVector();
this.vector[ this.effective_index++ ] = element;
}
private void growVector() {
Object[] replacementVector = new Object[ this.vector.length + QUANTA ];
// copy the contents of the existing vector into the replacement
// vector,
for( int index = 0; index < this.vector.length; index++ )
replacementVector[ index ] = this.vector[ index ];
this.vector = replacementVector;
}
// overrides ...
public String toString() {
StringBuilder str = new StringBuilder();
str.append("[ ");
/* why can't we just print from 0 through the effective_index? */
for( int index = 0; index < this.effective_index; index++ )
str.append( this.vector[ index ].toString() +", " );
str.append("]");
return str.toString();
}
}