Chapter 34

Package java.util


CONTENTS


In this chapter you learn about the util package. This package provides some of the most useful Java classes that you will come to rely on. It introduces ten classes, two exception classes, and two interfaces, as shown in Table 34.1. Figure 34.1 provides a graphical representation of the hierarchy of these contents.

Figure 34.1: Contents of package java.util

Table 34.1. Contents of package java.util.

Class IndexInterface Index Exception Index
BitSet Enumeration EmptyStackException
Date Observer NoSuchElementException
Dictionary   
Hashtable   
Observable   
Properties   
Random   
Stack   
StringTokenizer   
Vector   

The BitSet class is useful for storing and manipulating arbitrarily long sets of bits. The Date class can be used to represent dates and times and provides methods for converting dates to and from Strings. The abstract class Dictionary is a superclass of Hashtable. The Hashtable class can be used for creating an array of keys and values and allowing elements to be looked up by either key or value. The Properties class extends Hashtable in a couple of significant ways, most notably by allowing elements to be streamed into or out of the class. The Observable class can be extended and allows you to create new classes that notify other classes when they change. The Random class is a pseudo-random number generator that can return integer, floating-point or Gaussian-distributed values. The Stack class is an extension of Vector and supplies a last-in, first-out data structure. The Vector class can be used for storing any objects and can store objects of more than one type in the same vector. The StringTokenizer class provides a very flexible mechanism for parsing Strings.

In addition to these classes the util package also includes two interfaces: Enumeration and Observer. The Enumeration interface provides two methods that allow for easy traversal through a set of items. The Observer interface can be implemented by any class that needs to observe a subclass of Observable.

BitSet

Object

Cloneable

The class java.util.BitSet is derived directly from Object but also implements the Cloneable interface, as shown in Listing 34.1.


Listing 34.1. The BitSet class.
public class BitSet extends Object implements Cloneable {
  // public constructors
     public BitSet();
     public BitSet(int nbits);
  // public instance methods
     public void and(BitSet set);
     public void clear(int bit);
     public Object clone();
     public boolean equals(Object obj);
     public boolean get(int bit);
     public int hashCode();
     public void or(BitSet set);
     public void set(int bit);
     public int size();
     public String toString();
     public void xor(BitSet set);
}

This class represents a dynamically sized set of bits. Two constructors are provided: one that creates an empty set of unspecified size and one that creates a set of a specified size. The set method can be used to set an individual bit or clear can be used to clear an individual bit. The first bit in a BitSet is the zero bit so that myBitset.set(0) is a valid statement.

The logical functions and, or, and xor are all supported and will combine the BitSet with another set. BitSets can be compared for equality using equals and can be converted to strings using toString. For the purpose of converting a BitSet to a String, a set bit is represented by the value 1 and a clear bit is represented by 0.

BitSet

BitSet

public BitSet()

This constructor creates an empty bit set.

BitSet

BitSet

public BitSet(int nbits)

This constructor creates an empty bit set with the specified number of bits.

nbits is the number of bits in the set.

and

BitSet

public void and(BitSet set)

This method logically ANDs the BitSet with another BitSet. For example, the following code results in only bit 4 being set in bits1:

BitSet bits1 = new BitSet(10);
bits1.set(1);
bits1.set(4);

BitSet bits2 = new BitSet(10);
bits2.set(4);
bits2.set(5);
bits1.and(bits2);

set is the bit set to AND with the current set.

clear

BitSet

public void clear(int bit)

Clears the specified bit.

bit is the bit to clear.

clone

BitSet

public Object clone()

This method overrides the clone method in Object. It can be used to clone the bit set. For example, the following code creates a duplicate copy of bits in clonedBits:

BitSet bits = new BitSet(10);
bits.set(0);
bits.set(1);
bits.set(5);
BitSet clonedBits = (BitSet)bits.clone();

equals

BitSet

public boolean equals(Object obj)

This method can be used to compare the contents of two BitSets. If the same bits are set in the two BitSets, they are considered equal. Consider the following code sample:

BitSet bits1 = new BitSet(10);
bits1.set(0);
bits1.set(1);
bits1.set(4);

BitSet bits2 = new BitSet(10);
bits2.set(0);
bits2.set(1);
bits2.set(4);

BitSet bits3 = new BitSet(10);
bits3.set(0);
bits3.set(1);
bits3.set(5);

Graphics g = getGraphics();
if (bits1.equals(bits2))
    g.drawString("bits1 equals! bits2", 15, 15);
if (bits1.equals(bits3))
    g.drawString("bits1 equals! bits3", 15, 30);

In this case, bits1 will equal bits2 because the same bits are set; however, bits1 will not equal bits3.

obj is a bit set to compare against.

true if the set bits are the same; false, otherwise.

get

BitSet

public boolean get(int bit)

Gets the value of a specified bit in the set.

bit is the bit to get.

true if the bit is set; false if it is clear.

hashCode

BitSet

public int hashCode()

This method overrides the hashCode method in Object and can be used to get a hash code for the instance.

A hash code for the instance.

or

BitSet

public void or(BitSet set)

This method logically ORs the BitSet with another. For example, the following code results in bits 1, 4, and 5 being set in bits1:

BitSet bits1 = new BitSet(10);
bits1.set(1);
bits1.set(4);
BitSet bits2 = new BitSet(10);
bits2.set(4);
bits2.set(5);

bits1.or(bits2);

set is the bit set to OR with the current set.

set

BitSet

public void set(int bit)

Sets the specified bit.

bit is the bit to set.

size

BitSet

public int size()

This method returns the amount of space, in bits, used to store the set. Space for a bit set is allocated in 64-bit increments, so the following example will indicate that len1 equals 64 and len2 equals 128:

BitSet bits1 = new BitSet();
bits1.set(0);
bits1.set(1);
bits1.set(4);

BitSet bits2 = new BitSet(65);
bits2.set(0);
bits2.set(1);
bits2.set(5);

int len1 = bits1.size();       // will equal 64
int len2 = bits2.size();       // will equal 128

The amount of space, in bits, used to store the bit set.

toString

BitSet

public String toString()

This method formats the BitSet as a String. The String will consist of an opening curly brace, comma-separated values representing each set bit, and a closing curly brace. For example, the following code places {0, 1, 4} in the variable str:

BitSet bits1 = new BitSet();
bits1.set(0);
bits1.set(1);
bits1.set(4);
String str = bits1.toString();

A string representing the bits in the bit set that are set.

xor

BitSet

public void xor(BitSet set)

This method logically XORs the BitSet with another BitSet. For example, the following code results in bits 4 and 5 being set in bits1:

BitSet bits1 = new BitSet(10);
bits1.set(0);
bits1.set(1);
bits1.set(4);

BitSet bits2 = new BitSet(10);
bits2.set(0);
bits2.set(1);
bits2.set(5);

bits1.xor(bits2);

set is the bit set to XOR with the current set.

Date

Object

The class java.util.Date extends Object. The Date class stores a representation of a date and time and provides methods for manipulating the date and time components. A new Date instance may be constructed using any of the following:

Dates can be compared with the before, after, and equals methods. Methods are also provided for converting a date into various formatted Strings. The non-private interface of the Date class is shown in Listing 34.2.


Listing 34.2. The Date class.
public class Date extends Object {
  // public constructors
     public Date();
     public Date(long date);
     public Date (int year, int month, int date);
     public Date (int year, int month, int date,int hrs,int min);
     public Date (int year, int month, int date, int hrs,
             int min, int sec);
     public Date (String s);
  // static methods
     public static long UTC(int year, int month, int date, 
             int hrs, int min, int sec);
     public static long parse(String s);
  // public instance methods
     public int getYear();
     public void setYear(int year);
     public int getMonth();
     public void setMonth(int month);
     public int getDate();
     public void setDate(int date);
     public int getDay();
     public int getHours();
     public void setHours(int hours);
     public int getMinutes();
     public void setMinutes(int minutes);
     public int getSeconds();
     public void setSeconds(int seconds);
     public long getTime();
     public void setTime(long time);
     public boolean before(Date when);
     public boolean after(Date when);
     public boolean equals(Object obj);
     public int hashCode();
     public native String toString();
     public native String toLocaleString();
     public native String toGMTString();
     public int getTimezoneOffset();
}

Date

Date

public Date()

This method creates a new Date object using today's date. For example, to display today's date you could write the following:

Date today = new Date();
Graphics g = getGraphics();
g.drawString("Today is " + today, 15, 15);

Date

Date

public Date(long date)

This method creates a Date from a long that represents the number of milliseconds since January 1, 1970.

date is the number of milliseconds since January 1, 1970.

Date

Date

public Date(int year, int month, int date)

This method creates a new Date object that corresponds to the year, month, and day passed to it. The first month of the year is month zero. The day of the month is normalized so that impossible dates become real dates. For example, you'd think badDate in the following code would be equal to November 33, 1996.

Date goodDate = new Date(95, 10, 14);   // November 14, 1995    
Date badDate = new Date(96, 10, 33);    // December 3, 1996

However, badDate is adjusted to be December 3, 1996 instead. The value in goodDate will correctly be November 14, 1995.

year is the number of years since 1900.

month is the zero-based month, from 0-11.

date is the day of the month.

Date

Date

public Date(int year, int month, int date, int hrs, int min)

This method creates a new Date object that corresponds to the year, month, day, hours, and minutes passed to it. As with the prior constructor, the day of the month is normalized so that impossible dates become real dates. For example, to create a variable named birthday that holds November 14, 1995 at 1:16 PM (13:16 in military time), you would use the following:

Date birthday = new Date(95, 10, 14, 13, 16);

year is the number of years since 1900.

month is the zero-based month, from 0-11.

date is the day of the month.

hrs is the zero-based number of hours (0-23).

min is the zero-based number of minutes (0-59).

Date

Date

public Date(int year, int month, int date, int hrs, int min, int sec)

This method creates a new Date object that corresponds to the year, month, day, hour, minute, and seconds passed to it. As with the other constructors, the day of the month is normalized so that impossible dates become real dates.

year is the number of years since 1900.

month is the zero-based month, from 0-11.

date is the day of the month.

hrs is the zero-based number of hours (0-23).

min is the zero-based number of minutes (0-59).

sec is the zero-based number of seconds (0-59).

Date

Date

public Date(String s)

This method creates a new date based on the date string passed to it. For example, to create a variable that represents August 31, 1996, you could use the following:

Date aDate = new Date("August 31 1996");

s is a time string in the format passed to java.util.Date.Parse, as described later in this chapter.

UTC

Date

public static long UTC(int year, int month, int date, int hrs, int min, int sec)

This method calculates the time in UTC (Coordinated Universal Time) format based on the specified parameters. Parameters are expected to be given in UTC values, not the time in the local time zone.

year is the number of years since 1900.

month is the zero-based month, from 0-11.

date is the day of the month.

hrs is the zero-based number of hours (0-23).

min is the zero-based number of minutes (0-59).

sec is the zero-based number of seconds (0-59).

A UTC time value.

Parse

Date

public static long parse(String s)

This method calculates the time in UTC format based on the string passed to it.

s is a formatted time string such as "Mon, 8 Apr 1996 21:32:PM PST". To specify the time zone, you can use any of the continental United States time zone abbreviations (est, edt, cst, cdt, mst, mdt, pst, pdt) or you can use "GMT" with an offset, such as the following:

Mon, 8 Apr 1996 21:32:PM GMT+0800

This calculates GMT plus eight hours. This method considers GMT and UTC to be equivalent and does not make adjustments for the periodic "leap seconds."

A UTC time value.

After

Date

public boolean after(Date when)

Determines whether the Date occurs after the specified date. For example, to determine if the United States Independence Day (July 4) is after the French Bastille Day (July 14), use the following code:

Date independenceDay = new Date(96, 6, 4);
Date bastilleDay = new Date(96, 6, 14);

Graphics g = getGraphics();
if (independenceDay.after(bastilleDay))
    g.drawString("Independence Day is after Bastille Day",15,15);
else
    g.drawString("Independence Day is before Bastille Day",15,15);

when is the date to compare against.

true if the object's date occurs after the specified date; false, otherwise.

Before

Date

public boolean before(Date when)

Determines whether the date occurs before the specified date.

when is the date to compare against.

true if the object's date occurs before the specified date; false, otherwise.

Equals

Date

public boolean equals(Object obj)

This method determines whether two date objects are the same by comparing the dates represented by each object. For example, the following code will verify that Independence Day and the Fourth of July are the same date:

Date independenceDay = new Date(96, 6, 4);
Date fourthOfJuly = new Date(96, 6, 4);

Graphics g = getGraphics();
if (independenceDay.equals(fourthOfJuly))
    g.drawString("They're equal", 15, 15);
else
    g.drawString("They're not equal", 15, 15);

obj is the object to compare against.

True if the dates are the same; false, otherwise.

GetDate

Date

public int getDate()

This method returns the day (or date) portion of a date object.

The day of the month from 1 to 31.

GetDay

Date

public int getDay()

This method returns the day of the week. Sunday is assigned a value of 0.

The day of the week from 0 (Sunday) to 6 (Saturday).

getHours

Date

public int getHours()

This method returns the hours.

The hours from 0 to 23.

getMinutes

Date

public int getMinutes()

This method returns the minutes.

The minutes from 0 to 59.

getMonth

Date

public int getMonth()

This method returns the month.

The month from 0 (January) to 11 (December).

getSeconds

Date

public int getSeconds()

This method returns the seconds.

The seconds from 0 to 59.

GetTime

Date

public long getTime()

This method returns the number of milliseconds since midnight on January 1, 1970.

The time expressed in elapsed milliseconds.

GetTimezoneOffset

Date

public int getTimezoneOffset()

This method returns the offset in minutes of the current time zone from the UTC. For example, California is in the Pacific time zone and during Pacific Standard Time the following will display that it is 480 minutes (8 hours) different from UTC:

Date date1 = new Date(96, 11, 14);

Graphics g = getGraphics();
g.drawString("Timezone Offset: " + date1.getTimezoneOffset()
        + " minutes from UTC", 15, 15);

The number of minutes difference between the time zone of the object and UTC.

GetYear

Date

public int getYear()

This method returns the year after 1900.

The year after 1900.

HashCode

Date

public int hashCode()

This method overrides the hashCode method in Object and can be used to get a hash code for the instance.

A hash code for the instance.

setDate

Date

public void setDate(int date)

This method sets the day of the month portion of a Date object.

date is the day value.

SetHours

Date

public void setHours(int hours)

This method sets the hours portion of a Date object.

hours is the hours from 0 (midnight) to 23.

SetMinutes

Date

public void setMinutes(int minutes)

This method sets the minutes portion of a Date object.

minutes is the minutes from 0 to 59.

SetMonth

Date

public void setMonth(int month)

This method sets the month portion of a Date object.

month is the zero-based month from 0 (January) to 11 (December).

SetSeconds

Date

public void setSeconds(int seconds)

This method sets the seconds portion of a Date object.

seconds is the seconds from 0 to 59.

SetTime

Date

public void setTime(long time)

This method sets the time to the time represented by the number of milliseconds in the time parameter. It is frequently used in conjunction with the getTime method, which returns a number of milliseconds. An example of using setTime in conjunction with getTime is as follows:

Date date1 = new Date(96, 11, 14);
long milliSeconds = date1.getTime();
Date date2 = new Date();
date2.setTime(milliSeconds);

if (date1.equals(date2)) {
    Graphics g = getGraphics();
    g.drawString("Dates are equal", 15, 15);
}

time is the new time in milliseconds since January 1, 1970.

SetYear

Date

public void setYear(int year)

This method sets the year portion of a date instance. As an example, consider the following code:

Date birthday = new Date(95, 10, 14);
birthday.setYear(100);
int day = birthday.getDay();
switch (birthday.getDay()) {
    case 0: // Sunday
        g.drawString("It will be a Sunday", 15, 15);
        break;
    case 1: // Monday
        g.drawString("It will be a Monday", 15, 15);
        break;
    case 2: // Tuesday
        g.drawString("It will be a Tuesday", 15, 15);
        break;
    case 3: // Wednesday
        g.drawString("It will be a Wednesday", 15, 15);
        break;
    case 4: // Thursday
        g.drawString("It will be a Thursday", 15, 15);
        break;
    case 5: // Friday
        g.drawString("It will be a Friday", 15, 15);
        break;
    case 6: // Saturday
        g.drawString("It will be a Saturday", 15, 15);
        break;
}

This example shows how to plan a birthday party in the year 2000. First, the variable birthday is set to November 14, 1995. Then, setYear is used to change the year to 2000 (1900 + 100). Finally, a switch statement on getDay is used to determine the day of the week.

Year is the year after 1900. For 1996, use 96.

ToGMTString

Date

public String toGMTString()

This method creates a string that contains the date and time formatted according to GMT (Greenwich Mean Time) conventions. For example, if run on a machine set to Pacific Standard Time, the following code will display "14 Nov 1995 08:00:00 GMT":

Date date1 = new Date(95, 10, 14);

Graphics g = getGraphics();
if (date1.equals(date1))
    g.drawString("GMT: " + date1.toGMTString(), 15, 15);

A string representing the date in GMT format, such as "14 Nov 1995 08:00:00 GMT".

ToLocaleString

Date

public String toLocaleString()

This method creates a string that contains the date and time in the format of the current locale. For example, the following code will display "11/14/95 00:00:00":

Date date1 = new Date(95, 10, 14);

Graphics g = getGraphics();
if (date1.equals(date1))
    g.drawString("Locale: " + date1.toLocaleString(), 15, 15);

A string representing the date as formatted for the locale of the instance, such as "11/14/95 00:00:00".

ToString

Date

public String toString()

This method creates a string that contains the day of the week, the date, and the time. For example, the following code will display "Tue Nov 14 00:00:00 1995":

Date date1 = new Date(95, 10, 14);

Graphics g = getGraphics();
if (date1.equals(date1))
    g.drawString("String: " + date1.toString(), 15, 15);

A string representing the day of the week, date, and time of the instance, such as "Tue Nov 14 00:00:00 1995".

Dictionary

Object

The abstract class java.util.Dictionary extends Object. The non-private members of Dictionary are shown in Listing 34.3.


Listing 34.3. The Dictionary class.
public class Dictionary extends Object {
  // public constructors
     public Dictionary();
  // public instance methods
     public abstract Enumeration elements();
     public abstract Object get(Object key);
     public abstract boolean isEmpty();
     public abstract Enumeration keys();
     public abstract Object put(Object key, Object value);
     public abstract Object remove(Object key);
     public abstract int size();
}

The Dictionary class is an abstract class. Hashtable is derived directly from Dictionary, and Properties is derived from Hashtable. Although one of these classes will probably meet your needs, you could extend Dictionary in your own new class if necessary.

Each element in a Dictionary consists of a key and value. Elements are added to a Dictionary using put and are retrieved using get. Elements may be deleted with remove. The methods elements and keys each return an enumeration of the values and keys, respectively, stored in the Dictionary.

Dictionary

Dictionary

public Dictionary()

This is a default constructor that will create an empty Dictionary.

elements

Dictionary

public abstract Enumeration elements()

This abstract method returns an Enumeration of all elements in a Dictionary.

An enumeration of each of the elements in the Dictionary. The methods of Enumeration can be used to iterate through the elements.

get

Dictionary

public abstract Object get(Object key)

This abstract method retrieves an object from a Dictionary based on its key.

key is the key of the object to be retrieved.

The value associated with the key, if found; null, if not.

isEmpty

Dictionary

public abstract boolean isEmpty()

This abstract method can be used to determine if the Dictionary is empty.

true if the Dictionary is empty; false, if not.

keys

Dictionary

public abstract Enumeration keys()

This abstract method returns an Enumeration of all keys in a Dictionary.

An enumeration of each of the keys in the Dictionary. The methods of Enumeration can be used to iterate through the keys.

put

Dictionary

public abstract Object put(Object key, Object value)

This abstract method inserts a new element into the Dictionary. To retrieve an element use the get method.

key is the key to be added.

value is the value associated with the key.

If the key was already in the Dictionary the old value associated with it is returned. If not, null is returned.

NullPointerException is thrown if the value to be put is null.

remove

Dictionary

public abstract Object remove(Object key)

This abstract method removes an object from a Dictionary.

key is the key of the element to be removed.

If the key is found, the value associated with it is returned; if not, null is returned.

size

Dictionary

public abstract int size()

This abstract method returns the number of elements in the Dictionary.

The number of items stored in the Dictionary.

Enumeration

The interface java.util.Enumeration defines methods that can be used to iterate through a set of objects. The methods hasMoreElements and nextElement are typically used in a loop that visits each item in the set. For example, the following code will iterate through each item in a Vector calling the method DoSomething for each element:

for (Enumeration e = myVector.elements() ; e.hasMoreElements() ;)
    DoSomething(e.nextElement());

The Enumeration interface is shown in Listing 34.4.


Listing 34.4. The Enumeration interface.
public interface Enumeration {
    // public instance methods
     public abstract boolean hasMoreElements();
     public abstract Object nextElement();

     }


hasMoreElements

Enumeration

public abstract boolean hasMoreElements()

Can be used to determine if the enumeration has more elements.

true if there are more elements; false, if not.

nextElement

Enumeration

public abstract Object nextElement()

This method returns the next element in the enumeration. Calling it repeatedly will move through the enumeration.

The next element in the enumeration.

NoSuchElementException is thrown if there are no more elements in the enumeration.

Hashtable

Dictionary

The class java.util.Hashtable extends Dictionary. The non-private members of Hashtable are shown in Listing 34.5.


Listing 34.5. The Hashtable class.
public class Hashtable extends Dictionary {
  // public constructors
     public Hashtable(int initialCapacity, float loadFactor);
     public Hashtable(int initialCapacity);
     public Hashtable();
  // public instance methods
     public synchronized void clear();
     public synchronized Object clone();
     public synchronized boolean contains(Object value);
     public synchronized boolean containsKey(Object key);
     public synchronized Enumeration elements();
     public synchronized Object get(Object key);
     public boolean isEmpty();
     public synchronized Enumeration keys();
     public synchronized Object put(Object key, Object value);
     public synchronized Object remove(Object key);
     public int size();
     public synchronized String toString();
  // protected instance methods
     protected void rehash();
}

A Hashtable is used for mapping keys to values. For example, it could be used to map names to ages, programmers to projects, job titles to salaries, and so on. The Properties class extends Hashtable and adds the ability to read and write a Hashtable to a stream.

Each element in a Hashtable consists of a key and value. Elements are added to a Hashtable using the put method and are retrieved using get. Elements may be deleted from a Hashtable with remove. A Hashtable expands in size as elements are added to it. When creating a new Hashtable, you can specify an initial capacity and a load factor. The Hashtable increases in size whenever adding a new element would move the Hashtable past its threshold. A Hashtable's threshold is its capacity multiplied by its load factor. For example, a Hashtable with a capacity of 100 and a load factor of 0.75 would have a threshold of 75 items.

Hashtable

Hashtable

public Hashtable(int initialCapacity, float loadFactor)

This constructor creates a new instance of a Hashtable with the specified initial capacity and load factor. Although an initial capacity is specified, the Hashtable grows as needed when new items are added. The initial capacity specifies how many elements could be stored in the Hashtable if the load factor is 1.0. The load factor is a number between 0.0 and 1.0 and specifies the percent of the Hashtable that must be full before the size is automatically increased.

initialCapacity is the initial capacity of the Hashtable.

loadFactor is a value between 0.0 and 1.0 which specifies the percent of available hash slots that can be filled before the table is automatically rehashed into a larger Hashtable.

Hashtable

Hashtable

public Hashtable(int initialCapacity)

This constructor creates a new Hashtable with the specified initial capacity and a default load factor of 0.75.

initialCapacity is the initial capacity of the Hashtable.

Hashtable

Hashtable

public Hashtable()

This constructor creates a new Hashtable using default values for the initial capacity and the load factor. A default of 101 is used for the initial capacity, and 0.75 is used for the load factor.

clear

Hashtable

public synchronized void clear()

This method removes all elements from a Hashtable. The following example creates a Hashtable, inserts three items into it, and then removes all of them using clear:

Hashtable ages = new Hashtable();
ages.put("Mike", new Integer(33));
ages.put("Laura", new Integer(34));
ages.put("Savannah", new Integer(0));
ages.clear();

clone

Hashtable

public synchronized Object clone()

This method clones the Hashtable into a new Hashtable. The keys and values themselves are not cloned. The following example results in the creation of two Hashtables, each with the same three elements:

Hashtable ages = new Hashtable();
ages.put("Mike", new Integer(33));
ages.put("Laura", new Integer(34));
ages.put("Savannah", new Integer(0));
Hashtable clonedAges = (Hashtable)ages.clone();

A cloned Hashtable.

contains

Hashtable

public synchronized boolean contains(Object value)

This method searches the Hashtable to determine if a specific value is stored. For example, consider the following example, which searches the ages Hashtable for anyone with an age of 0:

Hashtable ages = new Hashtable();
ages.put("Mike", new Integer(33));
ages.put("Laura", new Integer(34));
ages.put("Savannah", new Integer(0));

Graphics g = getGraphics();
if (ages.contains(new Integer(0)))
    g.drawString("Found a baby!", 15, 15);
else
    g.drawString("No babies found!", 15, 15);

value is the value to search for.

True if the value is found; false, if not.

NullPointerException is thrown if the value is null.

containsKey

Hashtable

public synchronized boolean containsKey(Object key)

This method searches the Hashtable to determine if a specific key occurs. As an example, consider the following code, which searches for the name Savannah:

Hashtable ages = new Hashtable();
ages.put("Mike", new Integer(33));
ages.put("Laura", new Integer(34));
ages.put("Savannah", new Integer(0));

Graphics g = getGraphics();
if (ages.containsKey("Savannah"))
    g.drawString("Savannah was found!", 15, 15);
else
    g.drawString("Savannah not found!", 15, 15);

key is the key to search for.

true if the key is found; false, if not.

elements

Hashtable

public synchronized Enumeration elements()

This method returns an enumeration of all of the element values in the instance. For example, the following code will display the integers 33, 34, and 0:

Hashtable ages = new Hashtable();
ages.put("Mike", new Integer(33));
ages.put("Laura", new Integer(34));
ages.put("Savannah", new Integer(0));

Graphics g = getGraphics();
int count = 0;
for (Enumeration enum = ages.elements() ; enum.hasMoreElements() ;) {
    count++;
    g.drawString("Value = " + (Integer)enum.nextElement(), 15, 15*count);
}

An enumeration of each of the keys in the Hashtable. The methods of Enumeration can be used to iterate through the keys.

get

Hashtable

public synchronized Object get(Object key)

This function retrieves the object associated with the specified key. For example, the following code puts three objects into a Hashtable and then retrieves Laura's age:

Hashtable ages = new Hashtable();
ages.put("Mike", new Integer(33));
ages.put("Laura", new Integer(34));
ages.put("Savannah", new Integer(0));

Integer age = (Integer)ages.get("Laura");

Graphics g = getGraphics();
if (age != null)
    g.drawString("Laura is " + age, 15, 15);

key is the key of the object to be retrieved.

The value associated with the key, if found; null, if not.

isEmpty

Hashtable

public boolean isEmpty()

This method can be used to determine if the Hashtable is empty.

true if the Hashtable is empty; false, if not.

keys

Hashtable

public synchronized Enumeration keys()

This method returns an enumeration of all of the keys in the instance. For example, the following code will display the names Mike, Laura, and Savannah:

Hashtable ages = new Hashtable();
ages.put("Mike", new Integer(33));
ages.put("Laura", new Integer(34));
ages.put("Savannah", new Integer(0));

Graphics g = getGraphics();
int count = 0;
for (Enumeration enum = ages.keys() ; enum.hasMoreElements() ;) {
    count++;
    g.drawString((String)enum.nextElement(), 15, 15*count);
}

An enumeration of each of the keys in the Hashtable. The methods of Enumeration can be used to iterate through the keys.

put

Hashtable

public synchronized Object put(Object key, Object value)

This method inserts a new element into the Hashtable. To retrieve an element use the get method. The following sample code creates a new Hashtable and then puts three elements into it:

Hashtable ages = new Hashtable();
ages.put("Mike", new Integer(33));
ages.put("Laura", new Integer(34));
ages.put("Savannah", new Integer(0));

key is the key to be added.

value is the value associated with the key.

If the key was already in the Hashtable, the old value associated with it is returned. If not, null is returned.

NullPointerException is thrown if the value is null.

rehash

Hashtable

protected void rehash()

This method rehashes the Hashtable into a larger Hashtable. It is not normally necessary to call this method directly because it is invoked automatically based on the capacity and load factor of the Hashtable.

remove

Hashtable

public synchronized Object remove(Object key)

This method removes an object from a Hashtable. The following code illustrates how to remove an element:

Hashtable ages = new Hashtable();
ages.put("Mike", new Integer(33));
ages.put("Laura", new Integer(34));
ages.put("Savannah", new Integer(0));
ages.remove("Laura");

key is the key of the element to be removed.

If the key is found, the value associated with it is returned; if not, null is returned.

size

Hashtable

public int size()

This method returns the number of elements in the Hashtable.

The number of items stored in the Hashtable.

toString

Hashtable

public synchronized String toString()

This method overrides the toString method in Object and formats the contents of the Hashtable as a String. For example, the following code will display {Savannah=0, Laura=34, Mike=33}:

Hashtable ages = new Hashtable();
ages.put("Mike", new Integer(33));
ages.put("Laura", new Integer(34));
ages.put("Savannah", new Integer(0));
Graphics g = getGraphics();
g.drawString(ages.toString(), 15, 15);

A String representation of the Hashtable.

Observable

Object

The class java.util.Observable extends Object directly. An Observable class is a class that may be watched or monitored by another class that implements the Observer interface. Associated with an Observable instance is a list of Observers. Whenever the Observable instance changes, it can notify each of its Observers. By using Observable and Observer classes, you can achieve a better partitioning of your code by decreasing the reliance of one class on another.

The non-private members of Observable are shown in Listing 34.6.


Listing 34.6. The Observable class.
public class Observable extends Object {
  // public constructors
     public Observable();
  // public instance methods
     public synchronized void addObserver(Observer o);
     public synchronized int countObservers();
     public synchronized void deleteObserver(Observer o);
     public synchronized void deleteObservers();
     public synchronized boolean hasChanged();
     public void notifyObservers();
     public synchronized void notifyObservers(Object arg);
// protected instance methods
     protected synchronized void clearChanged();
     protected synchronized void setChanged();
}

As an example of how Observable can be used, consider the following declaration of a class that extends Observable:

class Obsable extends Observable {
    private int secretNumber;

    public Obsable(int x) {
        secretNumber = x;
    }
    public void setSecretNumber(int x) {
        secretNumber = x;
        setChanged();
        notifyObservers(new Integer(secretNumber));
    }
}

The Obsable class stores a secret number, and whenever that number changes, all Observers are notified. No Observable class is complete without an Observer, so here is the Test class that extends Applet and implements the Observer interface:

public class Test extends Applet implements Observer {
    Integer secretNumber;

    public void update(Observable o, Object arg) {
        secretNumber = (Integer)arg;
    }

    public boolean mouseDown(Event e, int x, int y)   {
        Obsable obs = new Obsable(12);
        obs.addObserver(this);
        obs.setSecretNumber(23);

        Graphics g = getGraphics();
        g.drawString("Secret Number: " + secretNumber, 15, 35);
        return true;
    }

    public boolean handleEvent(Event event) {
        return super.handleEvent(event);
    }

    public void init() {
        super.init();
        setLayout(null);
        resize(230,190);
    }
}

The Test class contains an update method that is part of the Observer interface. This method is passed an Observable item and an Object as parameters. As shown in the declaration of Obsable, the Object is an Integer. Therefore, update casts the Object into an Integer and stores it in the instance variable secretNumber. The mouseDown method is used to test this code. When a mouse button is pressed, a new Obsable instance is created, the instance of Test is added as an Observer and the setSecretNumber method is called. This method in Obsable causes all Observers to be notified. Because Test is an Observer, its update method is invoked, and the new value for secretNumber (23) is stored. It is then displayed as evidence that update was called.

Observable

Observable

public Observable()

This is an empty, default constructor.

addObserver

Observable

public synchronized void addObserver(Observer o)

This method adds an Observer to the list of objects that are observing this instance. The observer must implement the Observer interface. Frequently, the Observer parameter passed to this method is the this implicit member variable, as shown in the following:

Obsable obs = new Obsable(12);
obs.addObserver(this);

o is the observer to add.

clearChanged

Observable

protected synchronized void clearChanged()

This method clears the internal flag that indicates an Observable instance has changed.

countObservers

Observable

public synchronized int countObservers()

This method counts the number of Observers that are observing the instance.

The number of Observers for the instance.

deleteObserver

Observable

public synchronized void deleteObserver(Observer o)

This method deletes an Observer from the list of Observers that are monitoring an Observable object. The Observer must have been previously added with addObserver.

o is the observer to delete.

deleteObservers

Observable

public synchronized void deleteObservers()

This method deletes all Observers of the Observable instance.

hasChanged

Observable

public synchronized boolean hasChanged()

This method can be used to query whether an Observable has changed.

true if an observable change has occurred; false, otherwise.

notifyObservers

Observable

public void notifyObservers()

This method notifies all Observers that a change has occurred in the Observable object. This results in a call to the update method in each Observer.

notifyObservers

Observable

public synchronized void notifyObservers(Object arg)

This method notifies all Observers that a change has occurred in the Observable object. This results in a call to the update method in each Observer to which arg will be passed.

arg is any object that can be used to convey information to the Observers.

setChanged

Observable

protected synchronized void setChanged()

This method sets an internal flag to indicate that an observable change has occurred within the instance.