Java Reference
In-Depth Information
Most of the methods in the Vector class listed in the UML diagram in Figure 20.10 are
similar to the methods in the List interface. These methods were introduced before the
Java Collections Framework. For example, addElement(Object element) is the same
as the add(Object element) method, except that the addElement method is synchro-
nized. Use the ArrayList class if you don't need synchronization. It works much faster
than Vector .
Note
The elements() method returns an Enumeration . The Enumeration interface
was introduced prior to Java 2 and was superseded by the Iterator interface.
Note
Vector is widely used in Java legacy code because it was the Java resizable array imple-
mentation before Java 2.
In the Java Collections Framework, Stack is implemented as an extension of Vector , as
illustrated in Figure 20.11.
java.util.Vector<E>
java.util.Stack<E>
+Stack()
+empty(): boolean
+peek(): E
+pop(): E
+push(o: E): E
+search(o: Object): int
Creates an empty stack.
Returns true if this stack is empty.
Returns the top element in this stack.
Returns and removes the top element in this stack.
Adds a new element to the top of this stack.
Returns the position of the specified element in this stack.
F IGURE 20.11
The Stack class extends Vector to provide a last-in, first-out data
structure.
The Stack class was introduced prior to Java 2. The methods shown in Figure 20.11 were
used before Java 2. The empty() method is the same as isEmpty() . The peek() method
looks at the element at the top of the stack without removing it. The pop() method removes
the top element from the stack and returns it. The push(Object element) method adds the
specified element to the stack. The search(Object element) method checks whether the
specified element is in the stack.
20.26 How do you create an instance of Vector ? How do you add or insert a new element
into a vector? How do you remove an element from a vector? How do you find the
size of a vector?
20.27 How do you create an instance of Stack ? How do you add a new element to a
stack? How do you remove an element from a stack? How do you find the size of
a stack?
20.28 Does Listing 20.1, TestCollection.java, compile and run if all the occurrences of
ArrayList are replaced by LinkedList , Vector , or Stack ?
Check
Point
 
 
Search WWH ::




Custom Search