24.16. Thread States

 
[Page 729 ( continued )]

22.7. The Vector and Stack Classes

The Java Collections Framework was introduced with Java 2. Several data structures were supported prior to Java 2. Among them were the Vector and Stack classes. These classes were redesigned to fit into the Java Collections Framework, but all their old-style methods are retained for compatibility.

Vector is the same as ArrayList , except that it contains synchronized methods for accessing and modifying the vector. Synchronized methods can prevent data corruption when a vector is accessed and modified by two or more threads concurrently. For the many applications that do not require synchronization, using ArrayList is more efficient than using Vector .

The Vector class implements the List interface. It also has the methods contained in the original Vector class defined prior to Java 2, as shown in Figure 22.15.

Figure 22.15. The Vector class in Java 2 implements List and also retains all the methods in the original Vector class.
(This item is displayed on page 730 in the print version)

Most of the additional methods in the Vector class listed in the UML diagram in Figure 22.15 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 addElement method is synchronized. 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 programming because it was the Java resizable array implementation before Java 2. Many of the Swing data models use vectors.



[Page 730]

In the Java Collections Framework, Stack is implemented as an extension of Vector , as illustrated in Figure 22.16.

Figure 22.16. 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 22.16 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.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net