Wednesday, June 27, 2007

Chapter 10 - The java.util Package

Chapter 10: The java.util Package

Objectives

This chapter helps you to prepare for the exam by covering the following objectives:

Know the important classes and interfaces provided by the java.util package.

.
The java.util package is a core Java package. This package has been expanded in JDK
1.2 to cover include several new classes and interfaces. Some of these classes and
interfaces will be on the certification exam. You need to become familiar with these classes
and interfaces in order to answer related exam questions.
Know what the Collections API is and how it is used. Make appropriate selection of collection
classes/interfaces to suit specified behavior requirements.

.
Several exam questions require you to be familiar with classes and interfaces that are part of
the new Collections API. You will be required to know how these classes are used and the
subclass relationships between these classes.
Know how the date-related classes of the java.util package are used.

.
Several exam questions require knowledge of data-related classes, such as Calendar and
GregorianCalendar. You need to know the relationships between these classes and the
types of methods that they support to correctly answer some exam questions.
Know how other java.util classes and interfaces are used.

Although the certification exam focuses on Collections API classes of java.util, knowledge of other
classes and interfaces is important to being a good Java programmer. Familiarity with these other
classes and interfaces may help you answer some exam questions.

- 158



Study Strategies

As you read through this chapter, you should concentrate on the following key items:

.
The classes and interfaces are provided by java.util
.
How the Collections API is used
.
The class and inteface hierarchy supported by the Collections API
.
How the date-related classes of java.util are used
Chapter Introduction

This chapter covers the classes and interfaces of java.util package. Although you won't see a lot of
questions about this package, every question counts, and you should familiarize yourself with this
material. This chapter, like the exam, focuses on the new Collections API. It also covers date-related
classes and other prominent classes of java.util. If you read through this chapter and master the
review questions, you should have no problem with the java.util questions on the certification exam.

The Classes and Interfaces of the Java.Util Package

The java.util package provides 34 classes and 13 interfaces that support the new Collections API,
date/calendar operations, internationalization, change observation, parsing, random number generation,
and basic event processing. These classes and interfaces are organized as summarized in Figure 10.1
and described in the following sections.

The Collections API

The most notable change to the java.util package in JDK 1.2 is the introduction of the classes and
interfaces of the Collections API. These classes and interfaces provide an implementation-independent
framework for manipulating collections of objects. You'll first review the pre-JDK 1.2 collections classes
and interfaces,and then you'll cover the new classes and interfaces introduced with JDK 1.2.


Figure 10.1: The classes and interfaces of java.util.

- 159



Pre-JDK 1.2 Collections Classes and Interfaces

JDK 1.1 provided the Enumeration interface and the following six classes for working with collections
of objects:

.
Vector—An expandable array of objects
.
Stack—A last-in, first-out stack of objects
.
BitSet—A growable bit vector
.
Dictionary—A list of key-value pairs
.
Hastable—A dictionary that implements a hash table
.
Properties—A hash table that provides the capability to associate a list of properties
with their values
The Enumeration interface and the preceding six classes are very valuable in working with different
types of object collections. Their success inspired the JDK 1.2 Collections API. The following
subsections cover the Enumeration interface and the six classes in the preceding list.

The Enumeration Interface

The Enumeration interface provides two methods for stepping through an ordered set of objects or
values: hasMoreElements() and nextElement(). The hasMoreElements() method enables you
to determine whether more elements are contained in an Enumeration object. The nextElement()
method returns the nextElement() contained by an object.
Enumeration-implementing objects are said to be consumed by their use. This means that the
Enumeration objects cannot be restarted to reaccess through the elements they contain. Their
elements may be accessed only once.

Note Enumeration and Iterator The Enumeration interface has been replaced by

the Iterator interface in the JDK 1.2 Collections API. You can still use

Enumeration, but it is being phased out.

The Vector Class

The Vector class provides the capability to implement a growable array. The array grows larger as
more elements are added to it. The array may also be reduced in size after some of its elements have
been deleted. This is accomplished using the trimToSize() method.
Vector operates by creating an initial storage capacity and then adding capacity to this as needed. It
grows by an increment defined by the capacityIncrement variable. The initial storage capacity and
capacityIncrement can be specified in Vector's constructor. A second constructor is used when
you want to specify only the initial storage capacity. A third, default constructor specifies neither the
initial capacity nor the capacityIncrement. This constructor lets Java figure out the best parameters
to use for Vector objects. Finally, a fourth constructor was added with JDK 1.2 to create a Vector out
of a Collection object.
The access methods provided by the Vector class support array-like operations and operations related
to the number of objects contained in a Vector. The array-like operations enable elements to be
added, deleted, and inserted into vectors. They also allow tests to be performed on the contents of
vectors and specific elements to be retrieved. The size-related operations enable the byte size and
number of elements of the vector to be determined. It also enables the vector size to be increased to a
certain capacity or trimmed to the minimum capacity needed. (A vector's capacity is the number of
elements it can hold. Its size is the number of elements it does hold.) Consult the Vector API page for
a complete description of these methods.

Note Vector Update The Vector class has been retrofitted in JDK 1.2 to extend the

AbstractList class and implement the List interface.

The Stack Class

The Stack class provides the capability to create and use storage objects called stacks within your
Java programs. You store information by pushing it onto a stack and remove and retrieve information by
popping it off the stack. Stacks implement a last-in-first-out storage capability. The last object pushed
onto a stack is the first object that can be retrieved from the stack. The Stack class extends the
Vector class.
The Stack class provides a single default constructor, Stack(), that is used to create an empty stack.
Objects are placed on the stack using the push() method and retrieved from the stack using the
pop() method. The search() method enables you to search through a stack to see if a particular
object is contained on the stack. The peek() method returns the top element of the stack without
popping it off. The empty() method is used to determine whether a stack is empty. The pop() and
peek() methods both throw the EmptyStackException if the stack is empty. Use of the empty()
method can help to avoid the generation of this exception.

- 160



The BitSet Class

The BitSet class is used to represent and manipulate a set of bits. Each individual bit is represented
by a boolean value, and can be indexed much like an array or Vector. A bit set is a growable set, the
capacity of which is increased as needed. The bits of a bit set are sometimes referred to as flags.
Two BitSet constructors are provided. One enables the initial capacity of a BitSet object to be
specified. The other is a default constructor that initializes a BitSet to a default size.
The BitSet access methods provide and, or, and exclusive or logical operations on bit sets, enable
specific bits to be set and cleared, and override general methods declared for the Object class.

The Dictionary Class

The Dictionary, Hashtable, and Properties classes are three generations of classes that
implement the capability to provide key-based data storage and retrieval. The Dictionary class is the
abstract superclass of Hashtable, which is, in turn, the superclass of Properties.
Dictionary provides the abstract functions used to store and retrieve objects by key-value
associations. The class allows any object to be used as a key or value. This provides great flexibility in
the design of key-based storage and retrieval classes. Hashtable and Properties are two examples
of these classes.
The Dictionary class can be understood using its namesake. A hard-copy dictionary maps words to
their definitions. The words can be considered the keys of the dictionary, and the definitions are the
values of the keys. Java dictionaries operate in the same fashion. One object is used as the key to
access another object. This abstraction will become clearer as you investigate the Hashtable and
Properties classes.
The Dictionary class defines several methods that are inherited by its subclasses. The elements()
method is used to return an Enumeration object containing the values of the key-value pairs stored
within the dictionary. The keys() method returns an enumeration of the dictionary keys. The get()
method is used to retrieve an object from the dictionary based on its key. The put() method puts a
Value object in the dictionary and indexes it using a Key object. The isEmpty() method determines
whether a dictionary contains any elements, and the size() method identifies the dictionary's size in
terms of the number of elements it contains. The remove() method deletes a key-value pair from the
dictionary, based on the object's key.

Note Dictionary is Obsolete The Dictionary class has been rendered obsolete by

the Map interface, as of JDK 1.2. However, its Hashtable and Properties

subclasses are still in use.

The Hashtable Class

The Hashtable class implements a hash table data structure. A hash table indexes and stores objects
in a dictionary using hash codes as the objects' keys. Hash codes are integer values that identify
objects. They are computed in such a manner that different objects are very likely to have different hash
values and, therefore, different dictionary keys.
The Object class implements the hashCode() method. This method enables you to calculate the
hash code of an arbitrary Java object. All Java classes and objects inherit this method from Object.
The hashCode() method is used to compute the hash code key for storing objects within a hash table.
Object also implements the equals() method. This method is used to determine whether two objects
with the same hash code are, in fact, equal.
The Java Hashtable class is very similar to the Dictionary class from which it is derived. Objects
are added to a hash table as key-value pairs. The object used as the key is hashed, using its
hashCode() method, and the hash code is used as the actual key for the value object. When an
object is to be retrieved from a hash table, using a key, the key's hash code is computed and used to
find the object.
The Hashtable class provides three constructors. The first constructor allows a hash table to be
created with a specific initial capacity and load factor. The load factor is a float value between 0.0
and 1.0 that identifies the percentage of hash table usage that causes the hash table to be rehashed
into a larger table. For example, suppose a hash table is created with a capacity of 100 entries and a

0.70 load factor. When the hash table is 70 percent full, a new, larger hash table will be created, and the
current hash table entries will have their hash values recalculated for the larger table.
The second Hashtable constructor just specifies the table's initial capacity and ignores the load factor.
The default hash table constructor does not specify either hash table parameter.
The methods defined for the Hashtable class allow key-value pairs to be added to and removed from
a hash table. These methods are also used to search the hash table for a particular key or object value,
to create an enumeration of the table's keys and values, to determine the size of the hash table, and to
- 161



recalculate the hash table as needed. Many of these methods are inherited or overridden from the
Dictionary class.

The Properties Class

The Properties class is a subclass of Hashtable that can be read from or written to a stream. It also
provides the capability to specify a set of default values to be used if a specified key is not found in the
table. The default values themselves are specified as an object of class Properties. This allows an
object of class Properties to have a default Properties object, which in turn has its own default
properties, and so on.
Properties supports two constructors: a default constructor with no parameters and a constructor that
accepts the default properties to be associated with the Properties object being constructed.
The Properties class declares several new access methods. The getProperty() method enables
a property to be retrieved using a String object as a key. A second overloaded getProperty()
method allows a value string to be used as the default, in case the key is not contained in the
Properties object.
The load() and save() methods are used to load a Properties object from an input stream and
save it to an output stream. The save() method enables an optional header comment to be saved at
the beginning of the saved object's position in the output stream.
The propertyNames() method provides an enumeration of all the property keys, and the list()
method provides a convenient way to print a Properties object on a PrintStream object.

JDK 1.2 Collections Classes and Interfaces

The Collections API of JDK 1.2 added 10 new interfaces and 14 new classes to those that you studied
in the previous section. These additional classes and interfaces provide a powerful API for working with
different types of object collections.

The new Collections interfaces introduced with JDK 1.2 are as follows:

.
Collection—Defines methods that implement the concept of an unordered group of
objects, referred to as elements. The Collection interface corresponds to a
mathematical bag, which is a collection that allows duplicate objects. It defines a full
spectrum of methods for adding, removing, and retrieving objects from the collection, as
well as methods that operate on the collection itself.
.
List—Extends the Collection interface to implement an ordered collection of objects.
Because lists are ordered, List's objects can be indexed. The ListIterator interface
provides methods for iterating through the elements of a list.
.
Set—Extends the Collection interface to implement a finite mathematical set. Sets
differ from lists in that they do not allow duplicate elements.
.
SortedSet—A Set whose elements are sorted in ascending order.
.
Comparator—Provides a generic way to compare the elements of a collection.
.
Iterator—Provides methods for iterating through the elements of a collection. In JDK
1.2, the Iterator interface replaces the Enumeration interface.
.
ListIterator—Extends the Iterator interface to support bidirectional iteration of
lists.
.
Map—Replaces the Dictionary class as a means to associate keys with values. The
Map interface provides similar methods for performing operations on the map and its
elements.
.
SortedMap—A Map whose elements are sorted in ascending order.
.
Map.Entry—An inner interface of the Map interface that defines methods for working
with a single key-value pair.
Figure 10.2 shows the hierarchical relationships between the classes and interfaces of the Collections
API.

- 162



Figure 10.2: The Collections API class and interface hierarchy.

The new collections classes introduced with JDK 1.2 are as follows:

.
AbstractCollection— The AbstractCollection class provides a basic
implementation of the Collection interface. It is extended by other classes that tailor
AbstactCollection to more specific implementations.
.
AbstractList—The AbstractList class extends the AbstractCollection class
to provide a basic implementation of the List interface.
.
AbstractSequentialList—The AbstractSequentialList class extends the
AbstractList class to provide a list that is tailored to sequential access, as opposed to
random access.
.
LinkedList—The LinkedList class extends the AbstractSequentialList class
to provide an implementation of a doubly linked list. A linked list is a list in which each
element references the next element in the list. A doubly linked list is a list in which each
element references both the previous and next elements in the list.
.
ArrayList—The ArrayList class extends AbstractList to implement a resizable
array.
.
AbstractSet—The AbstractSet class extends the AbstractCollection class to
provide a basic implementation of the Set interface.
.
HashSet—The HashSet class extends AbstractSet to implement a set of key-value
pairs. It does not allow the use of the null element.
.
TreeSet—The TreeSet class extends AbstractSet to implement the Set interface
using a TreeMap.
.
AbstractMap—The AbstractMap class provides a basic implementation of the Mapinterface.
.
HashMap—The HashMap class extends AbstractMap to implement a hash table that
supports the Map interface.
.
WeakHashMap—The WeakHashMap class extends AbstractMap to provide a hashtablebased
Map implementation with weak keys. An entry in a WeakHashMap is automatically
removed when its key is garbage collected.
.
TreeMap—The TreeMap class extends AbstractMap to implement a sorted binary tree
that supports the Map interface.
.
Arrays—The Arrays class provides static methods for searching and sorting arrays
and converting them to lists.
.
Collections—The Collections class provides static methods for searching,
sorting, and performing other operations on objects that implement the Collection
interface.
The right half of Figure 10.2 shows the Collections API class hierarchy. The following subsections show
how to work with the new Collections classes and interfaces. Four examples are provided that show you
how to work with lists, sets, maps, and the conversion capabilities of the Arrays class.

- 163



Working with Lists

Lists are collections whose objects are ordered. Because lists are ordered, their elements can be
indexed. Lists allow duplicate elements. Most lists allow the null value to be an element.
The ListApp program of Listing 10.1 shows how to create and use lists. This program creates a
LinkedList object that is referenced by the list variable. The add() method if used to add the
strings "is", "is", "a", and "a" to the LinkedList object. The add() method is then used to add
the null value to the list. The addLast() method is used to add "test" as the last element of the
list. The addFirst() method is used to add "This" as the first element of the list. The
displayList() method is then invoked to display the elements of the list.
The displayList() method displays the following results:

The size of the list is: 7

This

is

is

a

a

null

test
The displayList() method uses the size() method to determine the number of elements in the
list. It invokes the listIterator() method to return an object that implements the ListIterator
interface. The argument to the listIterator() method is the index of the first element of the list to
return in the ListIterator object. In this case, I used 0 so that the whole list would be returned.
The hasNext() method of the ListIterator interface is used to iterate through the list, and the
next() method is used to retrieve the next element of the list. Note that the list can contain the null
value, and special provisions are made for printing this value.

ListappListing 10.1: The Program

import java.util.*;

public class ListApp {

public static void main(String args[]){
LinkedList list = new LinkedList();
list.add("is");
list.add("is");
list.add("a");
list.add("a");
list.add(null);
list.addLast("test");
list.addFirst("This");
displayList(list);

}

- 164



static void displayList(LinkedList list) {
System.out.println("The size of the list is: "+list.size());
ListIterator i = list.listIterator(0);
while(i.hasNext()){

Object o = i.next()
;
if(o == null) System.out.println("null")
;
else System.out.println(o.toString())
;


}
}

}
Working with Sets

Sets differ from lists in that they are unordered and cannot contain duplicates of the same element. The
SetApp program, shown in Listing 10.2, illustrates the use of sets. It performs the same type of
processing as ListApp, but it does so using sets instead of lists.

SetappListing 10.2: The Program

import java.util.*;

public class SetApp {

public static void main(String args[]){
HashSet set = new HashSet();
set.add("This");
set.add("is");
set.add("is");
set.add("a");
set.add("a");
set.add(null);
set.add("test");
displaySet(set);

}
static void displaySet(HashSet set)
{


- 165



System.out.println("The size of the set is: "+set.size())
;
Iterator i = set.iterator()
;
while(i.hasNext())
{


Object o = i.next()
;
if(o == null) System.out.println("null")
;
else System.out.println(o.toString())
;


}
}

}
SetApp begins by creating an HashSet object and assigning it to the set variable. It then adds the
same elements to the set as ListApp did to its list. Note that because sets are not ordered, there are
no addFirst() and addLast() methods. The displaySet() method is invoked to display the set.
It displays the following results:

The size of the set is:
5
This
is
a
null
test


Note that the set did not allow duplicate elements, but did allow the null value as an element. The
displaySet() method uses the size() method to determine the number of elements in the set. It
uses the iterator() method to create an Iterator object. The Iterator object is used to step
through and display the elements of the set.

Working with Maps

Maps differ from lists and sets in that they are ordered collections of key-value pairs. Maps are a
generalization of the Dictionary, Hashtable, and Properties classes that you studied earlier in
this chapter. The MapApp program of Listing 10.3 uses an object of the TreeMap class to create a
sorted list of key-value pairs. The TreeMap class implements a sorted binary tree.

MapappListing 10.3: The Program

import java.util.*;

public class MapApp {
public static void main(String args[]){
TreeMap map = new TreeMap();
map.put("one","1");
map.put("two","2");

- 166



map.put("three","3");

map.put("four","4");

map.put("five","5");

map.put("six","6");

displayMap(map);
}
static void displayMap(TreeMap map) {

System.out.println("The size of the map is: "+map.size());

Collection c = map.entrySet);

Iterator i = c.iterator();

while(i.hasNext()){

Object o = i.next();

if(o == null) System.out.println("null");

else System.out.println(o.toString());

}
}

}
The MapApp program begins by creating a TreeMap object and assigning it to the map variable. It then
adds six key-value pairs to the map. These key-value pairs associate the names of the numbers from 1
through 6 with their values. The displayMap() method is then invoked to display the program's
results:

The size of the map is: 6
five=5
four=4
one=1
six=6
three=3
two=2

The displayMap() method uses the size() method to determine the number of elements (key-value
pairs) in the map. It invokes the entrySet) method to create a Collection object containing the
values of the map. The iterator() method of the Collection object is used to obtain an
Iterator object for the collection. The Iterator object is used to step through and display the
elements of the collection. You should note that the TreeMap object uses the key to sort its key-value
pairs.

Sorting and Converting

The Arrays and Collections classes provide a number of static methods for searching, sorting,
and converting arrays and Collection objects. The ConvertApp program of Listing 10.4 provides an

- 167



example of these capabilities. This program creates an array of names, sorts the array, converts it to a
list, and then displays the values of the list.

Listing 10.4: The Convertapp Program


import java.util.*;

public class ConvertApp {
public static void main(String args[]){
String strings[] = {"Jason","Emily","Lisa","Jamie","Pierre",

"Stanley","Gloria","Ben","Ken","Lela"}
;
Arrays.sort(strings)
;
List list = Arrays.toList(strings)
;
displayList(list)
;


}

static void displayList(List list) {
System.out.println("The size of the list is: "+list.size());
ListIterator i = list.listIterator(0);
while(i.hasNext()){

Object o = i.next()
;
if(o == null) System.out.println("null")
;
else System.out.println(o.toString())
;


}
}

}
ConvertApp begins by creating an array of first names. It then uses the static sort() method of
the Arrays class to sort the array. The toList() method of Arrays is invoked to convert the array to
a List object. The displayList() method is then invoked to display the list. Its output follows:

The size of the list is: 10
Ben
Emily
Gloria
Jamie
Jason
Ken

- 168



Lela

Lisa

Pierre

Stanley
The displayList() method uses the method of the List interface to determine the size of the list
and step through the elements of the list.

Date and Calendar-Related Classes

Another major set of classes supported by the java.util package are classes for working with dates
and calendars. The original JDK 1.0 provided the Date class to encapsulate date and time as an object.
In JDK 1.1, many of the functions of the Date class were deprecated in favor of more international
handling of date and time. The Calendar, GregorianCalendar, SimpleTimeZone, and TimeZone
classes were added to provide more comprehensive and international support of date and time. The
DateFormat class of the java.text package was also added to support international date formatting.

Note
Deprecation A deprecated API element is one that has been replaced by an
improved alternative. In most cases, the deprecated element may still be used.
However, compiler warnings are generated to inform you that an improved
alternative exists.

Date

The Date class encapsulates date and time information and enables date objects to be accessed in a
system-independent manner.
Four of the six Date JDK 1.0 constructors have been deprecated. Only the default constructor that
creates a Date object with the current system date and time, and a constructor that creates a Date
object from a long value, are not deprecated in JDK 1.2.
The access methods defined by the Date class support comparisons between dates and provide
access to specific date information, including the time zone offset. However, many of the JDK 1.0
methods have been deprecated in favor of methods provided by the Calendar and TimeZone classes.

Calendar

The Calendar class provides support for date conversions that were previously implemented by the
Date class. The support provided by Calendar is more comprehensive and international. The
Calendar class is an abstract class that can be extended to provide conversions for specific calendar
systems. The GregorianCalendar subclass supports the predominant calendar system used by
many countries.
The Calendar class provides two constructors: a default parameterless constructor that constructs a
calendar with the default TimeZone and Locale objects and a constructor that allows the TimeZone
and Locale objects to be specified. It supplies many constants for accessing days of the week, months
of the year, hours, minutes, seconds, milliseconds, and other values.
The Calendar class provides a number of methods for performing data comparisons, arithmetic, and
conversions. The getInstance() method returns a locale-specific calendar that is a
GregorianCalendar object, by default.

GregorianCalendar

The GregorianCalendar class is a subclass of the Calendar class that supports calendar
operations for most of the world. It supports the eras B.C. and A.D. by defining them as class constants.
It provides seven constructors that enable GregorianCalendar objects to be created using a
combination of different date, time, time zone, and locale values. Its methods override those provided by
the Calendar class.

TimeZone

The TimeZone class is used to encapsulate the notion of a time zone. It allows you to work in the local
time zone, as well as time zones that are selected by a time zone ID. The TimeZone class keeps track
of daylight savings time.
The TimeZone class provides a single, parameterless constructor that creates a TimeZone object
corresponding to the local time zone. The TimeZone class does not define any field variables.
The access methods of TimeZone allow you to get a list of available time zone IDs, retrieve the local
time zone (from the operating system), get the local time zone offset (and adjust it for daylight savings
time), and create TimeZone objects for other time zone IDs.

- 169



SimpleTimeZone

The SimpleTimeZone class extends TimeZone to provide support for GregorianCalendar objects.
It creates SimpleTimeZone objects using the time zone IDs and offsets defined in the TimeZone
class. It provides methods for changing the way daylight savings time is calculated.

DateApp

The DateApp program illustrates the use of the date-related classes covered in the previous sections. It
shows how Date, GregorianCalendar, and TimeZone objects are created and how to use their
methods to access date/time information. The DateApp program is presented in Listing 10.5.

Listing 10.5: Using Dates and Calendars


import java.util.*;

public class DateApp {

public static void main(String args[]){
Date today = new Date();
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(today);
System.out.println("Today: ");
displayDateInfo(cal);
cal.clear();
cal.set(2000,0,1);
System.out.println("\nNew Years Day 2000: ");
displayDateInfo(cal);

}

static void displayDateInfo(GregorianCalendar cal){
String days[] = {"","Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
String months[] = {"January","February","March","April","May",

"June","July","August","September","October","November",

"December"};
String am_pm[] = {"AM","PM"};
System.out.println("Year: "+cal.get(Calendar.YEAR));
System.out.println("Month: "+months[cal.get(Calendar.MONTH)]);
System.out.println("Date: "+cal.get(Calendar.DATE));
System.out.println("Day: "+days[cal.get(Calendar.DAY_OF_WEEK)]);
System.out.println("Hour: "+(cal.get(Calendar.HOUR)+12)%13);

- 170



System.out.println("Minute: "+cal.get(Calendar.MINUTE))
;
System.out.println("Second: "+cal.get(Calendar.SECOND))
;
System.out.println(am_pm[cal.get(Calendar.AM_PM)])
;
TimeZone tz=cal.getTimeZone()
;
System.out.println("Time Zone: "+tz.getID())
;


}


}
The program creates a Date object and a GregorianCalendar object using the default Date() and
GregorianCalendar() constructors. The Date object is assigned to the today variable, and the
GregorianCalendar object is assigned to the cal variable. The cal variable is updated with the
current date by invoking its setTime() method with the Date object stored in today. The
displayDateInfo() method is then invoked to display date and time information about the cal
variable.
The clear() method of the Calendar class is invoked to reset the date of the GregorianCalendarobject stored in cal. The set()

method is used to set its date to New Year's 2000. There are several
versions of the set() method, each of which takes a different set of parameters. The version used in
DateApp takes the year, month, and date as parameters. Note that the month value ranges from 0to
12, where the year and date values begin at 1. The displayDateInfo() method is invoked again to
display information about the new calendar date.
The displayDateInfo() method creates the days, months, and am_pm arrays to define string
values corresponding to the days of the week, months of the year, and a.m./p.m. It then prints a line
corresponding to date and time values. These values are retrieved using the get() method of the
Calendar class and the Calendar constants corresponding to date/time values. The
getTimeZone() method of Calendar is invoked to retrieve the local TimeZone object. The getID()
method of the TimeZone class is used to retrieve the local time zone ID string.

Internationalization Classes

The java.util package provides a number of classes that support internationalization. These classes
are not emphasized on the certification exam and are covered in this section somewhat briefly.

The LocaleClass

The Locale class supports internationalization by describing geographic, political, or cultural regions.
Locale objects are used to tailor program output to the conventions of that region. They are created
using the Locale() constructors, which take language and country arguments and an optional
variant argument. The variant argument is used to specify software-specific characteristics, such
as operating system or browser. The Locale class defines constants for the most popular languages
and countries. The access methods of Locale support the setting and retrieving of language, country,
and variant-related values.

The ResourceBundleClass

The ResourceBundle class also supports internationalization. ResourceBundle subclasses are
used to store locale-specific resources that can be loaded by a program to tailor the program's
appearance to the particular locale in which it is being run. Resource bundles provide the capability to
isolate a program's locale-specific resources in a standard and modular manner.
The ResourceBundle class provides a single parameterless constructor. The parent field variable is
used to identify the ResourceBundle class that is the parent of a particular class. This parent can be
set using the setParent() method. The parent is used to find resources that are not available in a
particular resource bundle.
The ResouceBundle methods are used to retrieve the resources that are specific to a particular locale.

- 171



The ListResourceBundleClass

The ListResourceBundle class extends the ResourceBundle class to simplify access to locale-
specific resources. It organizes resources in terms of an array of object pairs, where the first object is a
String key and the second object is the key's value. The getContents() method returns the key-
value array.

The PropertyResourceBundleClass

The PropertyResourceBundle class extends the ResourceBundle class to organize locale-
specific resources using a property file. An InputStream object is supplied to the
PropertyResourceBundle() constructor to enable reading of the property file.

Other Java.Util Classes and Interfaces

The java.util package contains a number of other classes and interfaces that provide capabilities for
many of your programs. These remaining classes and interfaces are covered in the following subsections.


The Random Class

The Random class provides a template for the creation of random number generators. It differs from the
random() method of the java.lang.Math class in that it allows any number of random number
generators to be created as separate objects. The Math.random() method provides a static
function for the generation of random double values. This static method is shared by all program
code.
Objects of the Random class generate random numbers using a linear congruential formula. Two
constructors are provided for creating Random objects. The default constructor initializes the seed of the
random number generator using the current system time. The other constructor allows the seed to be
set to an initial long value.
The Random class provides eight access methods, seven of which are used to generate random values.
The next(), nextInt(), nextLong(), nextFloat(), and nextDouble() methods generate
values for the numeric data types. The values generated by nextFloat() and nextDouble() are
between 0.0 and 1.0. The nextGaussian() method generates a Gaussian distribution of double
values with mean 0.0 and standard deviation 1.0. The nextBytes() method generates a random
byte array.
The setSeed() method is used to reset the seed of the random number generator.

The StringTokenizer Class

The StringTokenizer class is used to create a parser for String objects. It parses strings
according to a set of delimiter characters. It implements the Enumeration interface in order to provide
access to the tokens contained within a string.
StringTokenizer provides three constructors. All three have the input string as a parameter. The first
constructor includes two other parameters: a set of delimiters to be used in the string parsing and a
boolean value used to specify whether the delimiter characters should be returned as tokens. The
second constructor accepts the delimiter string, but not the return token's toggle. The last constructor
uses the default delimiter set consisting of the space, tab, newline, and carriage-return characters.
The access methods provided by StringTokenizer include the Enumeration methods,
hasMoreElements() and nextElement(), hasMoreTokens() and nextToken(), and
countTokens(). The countTokens() method returns the number of tokens in the string being
parsed.

Observer and Observable

The Observer interface and Observable class are used to implement an abstract system by which
observable objects can be observed by objects that implement the Observer interface. Observable
objects are objects that subclass the Observable class. These objects maintain a list of observers.
When an observable object is updated, it invokes the update() method of its observers to notify them
that it has changed state.
The update() method is the only method that is specified in the Observer interface. The method
takes the Observable object and a second notification message Object as its parameters.
The Observable class is an abstract class that must be subclassed by Observable objects. It
provides several methods for adding, deleting, and notifying observers and for manipulating change
status. These methods are described in the class's API page.

The EventObject Class and the EventListener Interface

The EventObject class is the top-level class of the Java event hierarchy. Events represent actions
that occur during the course of program execution. Most events are generated as the result of user

- 172



actions, such as mouse clicks and keyboard actions. The java.awt.event package declares event
classes that are subclasses of EventObject. The EventObject class contains a single constructor
that identifies the object that is the source of the event. This object is accessible through the source
field variable. The EventObject class also provides the getSource() method for accessing the
event source.

Event handlers handle events by responding to the the events' occurrence and providing feedback to
the user. Java 1.1 provided the capability to deliver events to specific objects—a capability that was
lacking in Java 1.0.
JDK 1.1 event handling makes use of special classes, called adapter classes, whose objects listen for
the occurrence of events on behalf of objects of other classes. These classes implement event listener
interfaces that specify methods for identifying and responding to the occurrence of related events. The
EventListener interface is the top-level interface that all listener interfaces must implement. It is an
empty interface and does not declare any methods.

The PropertyPermission Class

The PropertyPermission class is used to create permissions to access specific system properties.
You should not use this class yourself. Instead, specify property permissions in your local security
policy.

Chapter Summary

This chapter covered the classes and interfaces of the java.util package. It focused on the new
Collections API and presented several examples of how these classes are used. It also covered date-
related and other prominent classes and interfaces of java.util. You should now be prepared to test
your knowledge of these topics. The following review questions and exam questions will let you know
how well you understand this material and will give you an idea of how you'll do in related exam
questions. They'll also indicate which material you need to study further.

Key Terms

.. Collection
.. List
.. Map
.. Vector
.. Set
.. Stack
.. Hashtable
.. Dictionary
.. Iterator
.
Gregorian Calendar
.
Time Zone
.. Locale
.. Internationalization
.
Resource Bundle
Review Questions

1. What is the Collections API?
2. What is the Vector class?
3. What is the Stack class?
4. What is the Dictionary class?
5. What is the Collection interface?
- 173



6. What is the List interface?
7. What is the Map interface?
8. What is the Set interface?
9. What is an Iterator interface?
10. What is the GregorianCalendar class?
11. What is the SimpleTimeZone class?
12. What is the Locale class?
13. What is the ResourceBundle class?
14. How are Observer and Observable used?
15. Which java.util classes and interfaces support event handling?
Exam Questions

1. What changes are needed to make the following program compile?
2. import java.util.*;
3. class Question {
4. public static void main(String args[]) {
5. String s1 = "abc";
6. String s2 = "def";
7. Vector v = new Vector();
8. v.add(s1);
9. v.add(s2);
10. String s3 = v.elementAt(0) + v.elementAt(1);
11. System.out.println(s3);
12.
}
}
A. Declare Question as public.
B. Cast v.elementAt(0) to a String.
C. Cast v.elementAt(1) to an Object.
D. Import java.lang.
13. What output does the following program display?
14. import java.util.*;
15. class Question {
16. public static void main(String args[]) {
17. String s1 = "abc";
18. String s2 = "def";
19. Stack stack = new Stack();
20. stack.push(s1);
21. stack.push(s2);
22. try {
23. String s3 = (String) stack.pop() + (String) stack.pop();
24. System.out.println(s3);
25. }catch(EmptyStackException ex){
26. }
27. }
}

A. abcdef
B. defabc
C. abcabc
D. defdef
28. Which of the following extend the Collection interface?
A. Dictionary
B. List
C. Map
D. Set
- 174



29. Which JDK 1.1 interface is the Iterator interface intended to replace?
A. Runnable
B. Throwable
C. Enumeration
D. List
30. Which of the following may have duplicate elements?
A. Collection
B. List
C. Map
D. Set
31. Can a null value be added to a List?
A. Yes.
B. Yes, but only if the List is linked.
C. Yes, provided that the List is non-empty.
D. No.
32. What is the output of the following program?
33. import java.util.*;
34. class Question {
35. public static void main(String args[]) {
36. HashSet set = new HashSet();
37. String s1 = "abc";
38. String s2 = "def";
39. String s3 = "";
40. set.add(s1);
41. set.add(s2);
42. set.add(s1);
43. set.add(s2);
44. Iterator i = set.iterator();
45. while(i.hasNext()){
46. s3 += (String) i.next();
47. }
48. System.out.println(s3);
49.
}
}
A. abcdefabcdef
B. defabcdefabc
C. fedcbafedcba
D. defabc
50. What is the output of the following program?
51. import java.util.*;
52. class Question {
53. public static void main(String args[]) {
54. TreeMap map = new TreeMap();
55. map.put("one","1");
56. map.put("two","2");
57. map.put("three","3");
58. displayMap(map);
59. }
- 175



60. static void displayMap(TreeMap map) {
61. Collection c = map.entrySet();
62. Iterator i = c.iterator();
63. while(i.hasNext()){
64. Object o = i.next();
65. System.out.print(o.toString());
66. }
67. }
}

A.
onetwothree
B.
123
C.
one=1three=3two=
D.
onethreetwo
68. Which of the following java.util classes support internationalization?
A.
Locale
B.
ResourceBundle
C.
Country
D.
Language
69. Which of the following are true about Observer and Observable?
A.
Observer is an interface and Observable is a class?
B. When an Observable object is updated it invokes the update() method
of its observers.
C.
Observable objects must be GUI com-ponents.
D.
They are in the Collections API.
Answers to Review Questions

1.
The Collections API is a set of classes and interfaces that support operations on
collections of objects.
2.
The Vector class provides the capability to implement a growable array of objects.
3.
The Stack class implements a last-in first-out stack.
4.
The Dictionary class provides the capability to store key-value pairs.
5.
The Collection interface provides support for the implementation of a mathematical
bag—an unordered collection of objects that may contain duplicates.
6.
The List interface provides support for ordered collections of objects.
7.
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys
with values.
8.
The Set interface provides methods for accessing the elements of a finite mathematical
set. Sets do not allow duplicate elements.
9.
The Iterator interface is used to step through the elements of a Collection.
10. The GregorianCalendar provides support for traditional Western calendars.
11. The SimpleTimeZone class provides support for a Gregorian calendar.
12. The Locale class is used to tailor program output to the conventions of a particular
geographic, political, or cultural region.
13. The ResourceBundle class is used to store locale-specific resources that can be
loaded by a program to tailor the program's appearance to the particular locale in which
it is being run.
14. Objects that subclass the Observable class maintain a list of observers. When an
Observable object is updated it invokes the update() method of each of its
observers to notify the observers that it has changed state. The Observer interface is
implemented by objects that observe Observable objects.
15. The EventObject class and the EventListener interface support event processing.
Answers to Exam Questions

1.
B. The elementAt() method of Vector returns an Object reference.
2.
B. Stacks are last-in first out.
- 176



3.
B and D. Dictionary is a class. Map does not extend Collection.
4.
C. It is intended to replace the Enumeration interface.
5.
A and B. Neither a Map nor a Set may have duplicate elements.
6.
A. Yes, a null value may be added to any List.
7.
D. Sets may not have duplicate elements.
8.
C. A TreeMap sorts its elements by their keys.
9.
A and B. Country and Language are not java.util classes.
10. A and B. Observer and Observable are not part of the Collections API. They do not
have any relationship to GUI components.

No comments: