The following is the output produced by the program; notice how the exception handler for
EmptyStackExceptionis caught so that you can gracefully handle a stack underflow:
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
One other point: AlthoughStackis not deprecated, with the release of Java SE 6,
ArrayDequeis a better choice.
Dictionary
Dictionaryis an abstract class that represents a key/value storage repository and operates
much likeMap. Given a key and value, you can store the value in aDictionaryobject. Once
the value is stored, you can retrieve it by using its key. Thus, like a map, a dictionary can be
thought of as a list of key/value pairs. Although not currently deprecated,Dictionaryis
classified as obsolete, because it is fully superseded byMap. However,Dictionaryis still in
use and thus is fully discussed here.
With the advent of JDK 5,Dictionarywas made generic. It is declared as shown here:
class Dictionary<K, V>
Here,Kspecifies the type of keys, andVspecifies the type of values. The abstract methods
defined byDictionaryare listed in Table 17-17.
Chapter 17: java.util Part 1: The Collections Framework 493
Method Purpose
Enumeration<V> elements( ) Returns an enumeration of the values contained in the dictionar y.
V get(Objectkey) Returns the object that contains the value associated withkey.If
keyis not in the dictionar y, anullobject is returned.
boolean isEmpty( ) Returnstrueif the dictionar y is empty, and returnsfalseif it
contains at least one key.
Enumeration<K> keys( ) Returns an enumeration of the keys contained in the dictionar y.
V put(Kkey, Vvalue) Inserts a key and its value into the dictionar y. Returnsnullifkey
is not already in the dictionar y; returns the previous value
associated withkeyifkeyis already in the dictionar y.
V remove(Objectkey) Removeskeyand its value. Returns the value associated with
key. Ifkeyis not in the dictionar y, anullis returned.
int size( ) Returns the number of entries in the dictionar y.
TABLE 17-17 The Abstract Methods Defined byDictionary