Java Reference
In-Depth Information
Java Class Library: The Class Vector
6.14
The Java Class Library contains a class Vector , whose instances—called vectors—behave like a
resizable array.
Here are some constructors and methods that we will use to implement the ADT stack:
public Vector()
Creates an empty vector, or arraylike container, with an initial capacity of 10. When the vector
needs to increase its capacity, the capacity doubles.
public Vector( int initialCapacity)
Creates an empty vector with the specified initial capacity. When the vector needs to increase
its capacity, the capacity doubles.
public boolean add(T newEntry)
Adds a new entry to the end of this vector.
public T remove( int index)
Removes and returns the entry at the given index in this vector.
public void clear()
Removes all entries from this vector.
public T lastElement()
Returns the entry at the end of this vector.
public boolean isEmpty()
Returns true if this vector is empty.
public int size()
Returns the number of entries currently in this vector.
You can learn more about Vector at download.oracle.com/javase/7/docs/api/ .
Note: Java Class Library: The class Vector
The Java Class Library has the class Vector in the package java.util . A vector is analogous
to a resizable array in that its elements are indexed beginning with 0. You work with a vector
by using its methods.
Using a Vector to Implement the ADT Stack
6.15
Using a vector to contain a stack's entries is like using an array, but easier. We let the first element
of the vector reference the bottom entry of the stack. Thus, the vector looks like the array in
Figure 6-4b. We do not need to maintain an index to the top entry of the stack, however, as we can
infer this index from the vector's size, which is readily available. Also, the vector expands as neces-
sary, so we do not have to worry about this detail.
Since the implementation of Vector is based on an array that can be resized dynamically, the
performance of this implementation of the stack is like that of the array-based implementation
given in the previous section.
Note: If you use a vector to implement a stack, the vector's first element should reference
the stack's bottom entry. Then the last occupied location in the vector references the stack's
top entry.
 
 
 
Search WWH ::




Custom Search