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.

Observer

The interface java.util.Observer defines an update method that is invoked by an Observable object whenever the Observable object has changed and wants to notify its Observers. The Observer interface is shown in Listing 34.7.


Listing 34.7. The Observer interface.
public interface Observer {
    // public instance methods
     public abstract void update(Observable o, Object arg);
}

For an example of how to use an Observer with an Observable class, see the discussion of the Observable class earlier in this chapter.

update

Observer

public abstract void update(Observable o, Object arg)

This method is called whenever an Observable instance that is being observed invokes either of its notifyObservers methods.

o-The Observable object that is generating this message.

arg-Any additional information passed by the Observable object's notifyObservers method. This may be null.

Properties

Hashtable

The class java.util.Properties extends Hashtable, which extends Dictionary. The non-private members of Properties are shown in Listing 34.8.


Listing 34.8. The Properties class.
public class Properties extends Hashtable {
  // public constructors
     public Properties();
     public Properties(Properties defaults);
  // public instance methods
     public String getProperty(String key);
     public String getProperty(String key, String defaultValue);
     public void list(PrintStream out);
     public synchronized void load(InputStream in);
     public Enumeration propertyNames();
     public synchronized void save(OutputStream out, String header);
  // protected variables
     protected Properties defaults;
}

This class can be used to store keys and associated values. Through its save and load methods, Properties can be written to disk. This makes this class an excellent mechanism for storing configuration information between runs of a program. An example of a Properties file written by the save method is as follows:

#This is a header comment
#Sun Jun 02 15:01:48 1996
prop3=put three
prop2=put two
prop1=put one

Because Properties is a subclass of Hashtable, new key/value pairs are added by using the put method of Hashtable. The following example shows how to create an instance, put three properties into it, save it, and then reload the keys and values into a different instance:

// create a new instance
Properties props1 = new Properties();

// put three properties into it
props1.put("prop1", "put one");
props1.put("prop2", "put two");
props1.put("prop3", "put three");

// retrieve each of the three properties
String prop1 = props1.getProperty("prop1", "one");
String prop2 = props1.getProperty("prop2", "two");
String prop3 = props1.getProperty("prop3");

// save the properties to a file
props1.save(new FileOutputStream("test.ini"), "My header");

// create a new instance and read the file in from the file
Properties props2 = new Properties();
FileInputStream inStr = new FileInputStream("test.ini");
props2.load(inStr);

// retrieve a property from the second instance
String prop = props2.getProperty("prop2", "two");

Variable

protected Properties defaults

This member stores the default property values.

Properties

Properties

public Properties()

This constructor is used to create an empty, new instance of Properties as follows:

Properties myProps = new Properties();

Properties

Properties

public Properties(Properties defaults)

This constructor creates a new instance of Properties and will establish a set of default properties.

GetProperty

Properties

public String getProperty(String key)

This method is used to retrieve a property based on its key. If no matching key is found, the defaults are searched. If no match is found there either, null is returned. It can be used as follows:

String prop1 = myProps.getProperty("prop1");

key is the key of the property to retrieve.

The property associated with the key or null if there is no matching key.

GetProperty

Properties

public String getProperty(String key, String defaultValue)

This method is used to retrieve a property based on its key. If no match is found, the defaultValue is returned. It can be used as follows:

String prop1 = myProps.getProperty("prop1", "default");

key is the key of the property to retrieve.

defaultValue is the value to use if no matching key is found.

The property associated with the key or the defaultValue if there is no matching key.

list

Properties

public void list(PrintStream out)

This method lists all of the properties to the specified PrintStream. It is useful mainly while debugging.

out is the PrintStream where the properties are to be printed.

load

Properties

public synchronized void load(InputStream in) throws IOException

This method reads a set of properties from the specified InputStream. Used in conjunction with the save method, Properties can be written to disk at the end of a program run and then reloaded at the start of the next run. The following example illustrates how to load a Properties instance from a file named TEST.INI:

Properties props = new Properties();
FileInputStream inStr = new FileInputStream("test.ini");
props.load(inStr);

in is the InputStream from which the Properties are to be read.

IOException is if the specified file is not found or cannot be read.

propertyNames

Properties

public Enumeration propertyNames()

This method returns an enumeration of all the property names in the instance. For example, the following code displays the names of each of the three properties:

Properties props1 = new Properties();
props1.put("prop1", "put one");
props1.put("prop2", "put two");
props1.put("prop3", "put three");

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

An enumeration of each of the property names. The methods of Enumeration can be used to iterate through the property names.

save

Properties

public synchronized void save(OutputStream out, String header)

This method saves the Properties to an OutputStream. Because FileOutputStream is a subclass of OutputStream, this method can be used to write to a file. As an example of writing Properties to a file, consider the following code:

Properties props1 = new Properties();
props1.put("prop1", "put one");
props1.put("prop2", "put two");
props1.put("prop3", "put three");
props1.save(new FileOutputStream("test.ini"), "My header");

This example creates a Properties set with three values and then writes them to a file named TEST.INI. The file is written with the header text My header. In this case, TEST.INI appears as follows:

#My header
#Sun Jun 02 15:01:48 1996
prop3=put three
prop2=put two
prop1=put one

out is the OutputStream to which the Properties are to be written.

header is a header that will be sent to the OutputStream before the properties.

Random

Object

The class java.util.Random is derived directly from Object, as shown in Listing 34.9.


Listing. 34.9. The Random class.
public class Random extends Object {
  // public constructors
     public Random();
     public Random(long seed);
  // public instance methods
     public double nextDouble();
     public float nextFloat();
     public synchronized double nextGaussian();
     public int nextInt();
     public long nextLong();
     public synchronized void setSeed(long seed);
}

This class represents a pseudo-random number generator. Two constructors are provided: One takes a seed value as a parameter, and the other takes no parameters and uses the current time as a seed. Values can be retrieved from the generator using the following methods:

nextDouble

nextFloat

nextGaussian

nextInt

nextLong

random

Random

public random()

This constructor creates a new random number generator that is seeded based on the current time.

random

Random

public random(long seed)

This constructor creates a new random number generator based on the specified seed value. You should use this constructor rather than random() if a repeatable sequence of pseudo-random numbers is necessary. Even if a repeatable sequence of numbers is not necessary once a program is complete, it can frequently be useful during the debugging stages. A program that uses random numbers can be particularly difficult to debug. Because of this, you may want to consider providing a configuration setting that enables you to force a random number generator to a known seed.

A program can reset the seed of an already created instance by using the member method setSeed.

seed is the seed value.

nextDouble

Random

public double nextDouble()

This method retrieves the next number from the random number generator. The number will be a pseudo-random, uniformly distributed double between 0.0D and 1.0D.

A randomly distributed double between 0.0D and 1.0D.

nextFloat

Random

public float nextFloat()

This method retrieves the next number from the random number generator. The number will be a pseudo-random, uniformly distributed float between 0.0F and 1.0F.

A randomly distributed float between 0.0F and 1.0F.

nextGaussian

Random

public synchronized double nextGaussian()

This method retrieves the next value from the pseudo-random number generator. The value will be returned as a Gaussian-distributed double that has a mean of 0 and a standard deviation of 1.

A Gaussian-distributed double.

nextInt

Random

public int nextInt()

This method retrieves the next number from the random number generator. The number will be a pseudo-random int with a value that is uniformly distributed among all possible int values.

A randomly distributed int.

nextLong

Random

public long nextLong()

This method retrieves the next number from the random number generator. The number will be a pseudo-random long with a value that is uniformly distributed among all possible long values.

A randomly distributed long.

setSeed

Random

public synchronized void setSeed(long seed)

This method sets a seed value for the pseudo-random number generator. The seed value is used to determine the values that are generated. By setting a specific seed value, the random number generator can be coerced into generating a specific sequence of values.

seed is the seed value.

Stack

Vector

The class java.util.Stack extends the class java.util.Vector, which is described later in this chapter. This class implements a simple last-in, first-out stack. An item is stored on a stack by "pushing" it onto the stack. An item may subsequently be "popped" off the stack and used. The item popped off a stack will always be the most recently pushed item. The non-private interface of the class is shown in Listing 34.10.


Listing 34.10. The Stack class.
public class Stack extends Vector {
  // public constructors
     public Stack();
  // public instance methods
     public empty();
     public peek();
     public pop();
     public push(Object item);
     public search(Object o);
}

Because Stack extends the Vector class, no size is associated with a Stack instance. The Stack continues to grow in size as new items are pushed onto it. In addition to methods to push and pop items, a peek method is provided for looking at the next item, a search method is provided for scanning the Stack for a specific item, and an empty method is provided for determining whether more items are stored in the Stack.

Stack

Stack

public Stack()

There is no explicit constructor provided. To create a new Stack, use the default constructor as follows:

Stack myStack = new Stack();

empty

Stack

public boolean empty()

This method can be used to determine whether the Stack contains items.

true if the Stack is empty; false, otherwise.

peek

Stack

public Object peek()

This method can be used to peek at the top item on the Stack. It is similar to pop but does not remove the item from the Stack.

The item at the top of the Stack.

EmptyStackException is thrown if the Stack is empty.

pop

Stack

public Object pop()

This method retrieves the last item added to the Stack. To examine, but not remove, the top item in the Stack use the peek method.

The item at the top of the Stack.

EmptyStackException is thrown if the Stack is empty.

push

Stack

public Object push(Object item)

This method adds a new item to the Stack.

item is the item to push onto the Stack.

The item that was pushed onto the Stack.

search

Stack

public int search(Object o)

This method examines the Stack to see whether the specified object is in the Stack.

o is the object of the search.

The distance from the top of the Stack, or -1 if the item is not in the Stack.

StringTokenizer

Object

Enumeration

The class java.util.StringTokenizer extends Object and implements the Enumeration interface. A StringTokenizer can be used to parse a String into its constituent tokens. For example, each word in a sentence could be considered a token. However, the StringTokenizer class goes beyond the parsing of sentences. You can create a fully customized tokenizer by specifying the set of token delimiters when the StringTokenizer is created. For parsing text, the default whitespace delimiters are usually sufficient. However, you could use the set of arithmetic operators (+, *, /, and -) if parsing an expression.

Because StringTokenizer implements the Enumeration interface, it includes the hasMoreElements and nextElement methods. Additionally, the methods hasMoreTokens and nextToken are provided. The hasMoreTokens method is identical to hasMoreElements, except that you may prefer the method name. The same is true of nextToken and nextElement. The non-private interface of the class is shown in Listing 34.11.


Listing 34.11. The StringTokenizer class.
public class StringTokenizer extends Object implements Enumeration {
  // public constructors
     public StringTokenizer(String str, String delim, boolean returnTokens);
     public StringTokenizer(String str, String delim);
     public StringTokenizer(String str);
  // public instance methods
     public int countTokens();
     public boolean hasMoreElements();
     public boolean hasMoreTokens();
     public Object nextElement();
     public String nextToken();
    public String nextToken(String delim);
}

StringTokenizer

StringTokenizer

public StringTokenizer(String str, String delim, boolean returnTokens)

This constructor creates a new instance based on the String to be tokenized, the set of delimiters, and a flag indicating whether delimiters should be returned as tokens. The following example shows how to create a StringTokenizer for parsing simple math expressions:

String s = "4*3+2/4";
StringTokenizer st = new StringTokenizer(s, "*+/-", true);
Graphics g = getGraphics();
int tokenCount = 0;
while (st.hasMoreTokens()) {
    tokenCount++;
    g.drawString(st.nextToken(), 15, 15*tokenCount);
}

str is the String to be tokenized.

Delim is a String containing the delimiters to use when tokenizing the String.

ReturnTokens is true if the StringTokenizer should return delimiters as tokens; false, if not.

StringTokenizer

StringTokenizer

public StringTokenizer(String str, String delim)

This constructor creates a new instance based on the String to be tokenized and a set of delimiters. The following example shows how to create a StringTokenizer, which can be used on a comma-delimited String:

String s = "field1,field2,field3,and field 4";
StringTokenizer st = new StringTokenizer(s,",",false);
int tokenCount = 0;

Graphics g = getGraphics();
while (st.hasMoreTokens()) {
    tokenCount++;
    g.drawString(st.nextToken(), 15, 15*tokenCount);
}

str is the String to be tokenized.

delim is a String containing the delimiters to use when tokenizing the String.

StringTokenizer

StringTokenizer

public StringTokenizer(String str)

This constructor creates a new instance based on the String to be tokenized and the default set of delimiters. The default delimiters are the space, tab, newline, and carriage return characters.

countTokens

StringTokenizer

public int countTokens()

This method returns the number of remaining tokens.

The quantity of tokens remaining in the String being tokenized.

hasMoreElements

StringTokenizer

public boolean hasMoreElements()

This method can be used to determine whether the StringTokenizer contains more elements (tokens). This method is identical to hasMoreTokens and is a member of StringTokenizer because StringTokenizer implements the Enumeration interface.

true if there are more elements; false, otherwise.

hasMoreTokens

StringTokenizer

public boolean hasMoreTokens()

This method can be used to determine whether the StringTokenizer contains more tokens. It is identical to hasMoreElements.

true if there are more tokens; false, otherwise.

nextElement

StringTokenizer

public Object nextElement()

This method overrides nextElement in the Enumeration interface and exists because StringTokenizer implements that interface. It is identical to nextToken and returns the next token in the enumeration.

The next token in the enumeration.

NoSuchElementException is thrown if there are no more elements.

nextToken

StringTokenizer

public String nextToken()

This method returns the next token in the String that is being tokenized. Typically, it is used inside a loop that processes each token. For example, the following code uses whitespace delimiters to tokenize the string "This has four tokens" and displays each of the tokens:

String s = "This has four tokens";
StringTokenizer st = new StringTokenizer(s);

int tokenCount = 0;
Graphics g = getGraphics();
while (st.hasMoreTokens()) {
    tokenCount++;
    g.drawString(st.nextToken(), 15, 15*tokenCount);
}

The next token in the string being tokenized.

NoSuchElementException is thrown if there are no more tokens.

nextToken

StringTokenizer

public String nextToken(String delim)

This method changes the set of delimiter characters and then returns the next token. The new delimiter set remains in effect after this method completes.

delim is a String containing the new set of delimiters.

The next token in the string being tokenized.

NoSuchElementException is thrown if there are no more tokens.

Vector

Object

Cloneable

The class java.util.Vector extends the class java.util.Object and implements the Cloneable interface. A Vector is analogous to a linked list in other languages or class libraries. A Vector stores items of type Object, so it can be used to store instances of any Java class. A single Vector may store different elements that are instances of different classes. The non-private interface of the class is shown in Listing 34.12.


Listing 34.12. The Vector class.
public class Vector extends Object {
  // public constructors
     public Vector(int initialCapacity, int capacityIncrement);
     public Vector(int initialCapacity);
     public Vector();
  // public instance methods
     public final synchronized void addElement(Object obj);
     public final int capacity();
     public synchronized Object clone();
     public final boolean contains(Object elem);
     public final synchronized void copyInto(Object anArray[]);
     public final synchronized Object elementAt(int index);
     public final synchronized Enumeration elements();
     public final synchronized void ensureCapacity(int minCapacity);
     public final synchronized Object firstElement();
     public final int indexOf(Object elem);
     public final synchronized int indexOf(Object elem, int index);
     public final synchronized void insertElementAt(Object obj, int index);
     public final boolean isEmpty();
     public final synchronized Object lastElement();
     public final int lastIndexOf(Object elem);
     public final synchronized int lastIndexOf(Object elem, int index);
     public final synchronized void removeAllElements();
     public final synchronized boolean removeElement(Object obj);
     public final synchronized void removeElementAt(int index);
     public final synchronized void setElementAt(Object obj, int index);
     public final synchronized void setSize(int newSize);
     public final int size();
     public final synchronized String toString();
     public final synchronized void trimToSize();
  // protected variables
     protected int capacityIncrement;
     protected int elementCount;
     protected Object elementData[];
}

Vector

Vector

public Vector(int initialCapacity, int capacityIncrement)

This constructor creates a new instance of a Vector with space for initialCapacity elements initially. Memory for additional elements is allocated in blocks that each hold capacityIncrement elements. For example, to allocate a Vector that will hold 100 elements initially and will allocate space for ten more at a time, use the following code:

Vector myVector = new Vector(100, 10);

initialCapacity is the number of elements for which to allocate space when the object is created.

capacityIncrement is the number of additional elements for which to allocate space whenever additional space is needed.

Vector

Vector

public Vector(int initialCapacity)

This constructor creates a new instance of a Vector with space for initialCapacity elements. Whenever a new element that would exceed this capacity is added, the size of the vector is doubled.

initialCapacity is the number of elements for which to allocate space when the object is created.

Vector

Vector

public Vector()

This constructor creates a new instance of a Vector. Initially, the Vector has room for storing ten elements, but this increases automatically to accommodate new elements. Whenever a new element is added that exceeds this capacity, the size of the vector is doubled.

Variables

protected int capacityIncrement

This member stores the amount by which the Vector will be incremented each time it needs to grow. If capacityIncrement is 0, then the buffer does not grow by a fixed amount but instead, doubles whenever it needs to grow.

protected int elementCount

This member stores the number of elements in the Vector.

protected Object elementData[]

This member is the array where the Vector elements are stored.

addElement

Vector

public final synchronized void addElement(Object obj)

This method is used to insert new elements into the Vector. A Vector can store objects of different types. For example, to create a Vector holding three Dates and a Stack with three items pushed onto it, use the following code:

Vector myVector = new Vector();

myVector.addElement(new Date(95, 10, 14));
myVector.addElement(new Date(96, 10, 14));
myVector.addElement(new Date(97, 10, 14));

Stack s = new Stack();
s.push(new Integer(0));
s.push(new Integer(10));
s.push(new Integer(20));

myVector.addElement(s);

obj is the object to add to the vector.

capacity

Vector

public final int capacity()

The method returns the number of elements that will fit in the Vector before more space is allocated. For example, the variable qty in the following code will equal 15:

Vector myVector = new Vector(10, 5);
myVector.addElement(new Integer(1));
myVector.addElement(new Integer(2));
myVector.addElement(new Integer(3));
myVector.addElement(new Integer(4));
myVector.addElement(new Integer(5));
myVector.addElement(new Integer(6));
myVector.addElement(new Integer(7));
myVector.addElement(new Integer(8));
myVector.addElement(new Integer(9));
myVector.addElement(new Integer(10));
myVector.addElement(new Integer(11));
int qty = myVector.capacity();

In this example, qty equals 15 because of the 10 allocated by the constructor and the additional 5 allocated when the size of the Vector exceeded its initial capacity.

The number of elements that will fit in the currently allocated portion of the Vector.

clone

Vector

public synchronized Object clone()

This method overrides clone in Object and will clone the Vector. Only the Vector itself is cloned; the elements of the Vector are not cloned. The following example creates two duplicate Vectors, each containing the same three strings:

Vector vector1 = new Vector();
vector1.addElement(new String("first string"));
vector1.addElement(new String("second string"));
vector1.addElement(new String("third string"));

Vector vector2 = (Vector)vector1.clone();

A cloned copy of the Vector.

Contains

Vector

public final boolean contains(Object elem)

This method determines whether an object is stored in a Vector. In the following example, 2 is contained in the vector but 12 is not:

Vector myVector = new Vector();
myVector.addElement(new Integer(1));
myVector.addElement(new Integer(2));
myVector.addElement(new Integer(3));

Graphics g = getGraphics();
if (myVector.contains(new Integer(2)))
    g.drawString("it contains 2", 15, 15);
if (myVector.contains(new Integer(12)))
    g.drawString("it contains 12", 15, 30);

true if the object is stored in the Vector; false, otherwise.

copyInto

Vector

public final synchronized void copyInto(Object anArray[])

This method copies the elements of the Vector into an array. The following example copies the Vector into the array strArray and then displays the second string ("second string"):

String strArray[];

Vector vector1 = new Vector();
vector1.addElement(new String("first string"));
vector1.addElement(new String("second string"));
vector1.addElement(new String("third string"));

strArray = new String[vector1.size()];
vector1.copyInto(strArray);

Graphics g = getGraphics();
g.drawString("second array element is " + strArray[1], 15, 15);

anArray is the array into which the Vector elements will be copied.

elementAt

Vector

public final synchronized Object elementAt(int index)

This method retrieves the element located at the specified index within the Vector. The index into a Vector is zero-based, so the following example will display "second string":

Vector myVector = new Vector();
myVector.addElement(new String("first string"));
myVector.addElement(new String("second string"));
myVector.addElement(new String("third string"));

Graphics g = getGraphics();
g.drawString((String)myVector.elementAt(1), 15, 15);

index is the zero-based index number of the element to retrieve.

The element at the specified zero-based index.

ArrayIndexOutOfBoundsException is thrown if an invalid index is specified.

elements

Vector

public final synchronized Enumeration elements()

This method returns an Enumeration of the elements in the Vector, making it easy to iterate through the elements. As an example, consider the following code, which creates a Vector and then steps through an enumeration of the Vector displaying each item:

Vector vector1 = new Vector(5);
vector1.addElement(new String("Mike"));
vector1.addElement(new String("Laura"));
vector1.addElement(new String("Savannah"));

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

An Enumeration consisting of all the elements in the Vector.

EnsureCapacity

Vector

public final synchronized void ensureCapacity(int minCapacity)

This method ensures that the Vector has at least the specified minimum capacity. If the current capacity of the Vector is less than minCapacity, the size of the Vector is increased to hold at least minCapacity.

MinCapacity is the desired minimum capacity of the Vector.

FirstElement

Vector

public final synchronized Object firstElement()

This method retrieves the first element in the Vector. If the Vector is empty, an exception is thrown. It performs the same function as elementAt(0). As an example of its use, the following displays "first string":

Vector myVector = new Vector();
myVector.addElement(new String("first string"));
myVector.addElement(new String("second string"));
myVector.addElement(new String("third string"));

Graphics g = getGraphics();
g.drawString((String)myVector.firstElement(), 15, 15);

The element at the specified zero-based index.

NoSuchElementException is thrown if the Vector is empty.

indexOf

Vector

public final int indexOf(Object elem)

This method searches the Vector and returns the zero-based index number of the first matching object. The following example creates a Vector and then finds the element number (1) that matches the Integer 21 element:

Vector vector1 = new Vector();
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(21));
vector1.addElement(new Integer(31));
vector1.addElement(new Integer(11));

int index = vector1.indexOf(new Integer(21));

Graphics g = getGraphics();
g.drawString("Item found at index " + index, 15, 15);

Because this method always starts searching from the first element in the Vector, it can be used only to find the first matching index number. To find subsequent matching index numbers, use indexOf(Object elem, int index). Similarly, the methods lastIndexOf(Object elem) and indexOf(Object elem, int index) can be used for backward traversal of a Vector.

elem is the element for which you want to find the index.

The element number of the first element that matches elem; if no match is found, -1 is returned.

indexOf

Vector

public final synchronized int indexOf(Object elem, int index)

This method finds the first element in the Vector that matches elem starting at the element given by index. It is very useful for traversing a Vector searching for all elements matching a specific object. The following example demonstrates this by searching for the three integer elements with a value of 11:

Vector vector1 = new Vector();
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(21));
vector1.addElement(new Integer(31));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(21));

int index = 0;
int itemsFound = 0;
Integer findMe = new Integer(11);
Graphics g = getGraphics();
while (index != -1) {
    index = vector1.indexOf(findMe, index);
    if (index != -1) {
        itemsFound++;
        g.drawString("Matched element " + index, 15, itemsFound * 15);
        index++;    // move to the next element and continue search
    }
}

     g.drawString("Matching items: " + itemsFound, 15, itemsFound*15 + 15);

elem is the element for which you want to find the index.

index is the index number at which to start the search.

The element number of the first element that matches elem; if no match is found, -1 is returned.

insertElementAt

Vector

public final synchronized void insertElementAt(Object obj, int index)

This method, like addElement, is used to add a new element to a Vector. However, this method can be used to specify where in the Vector the new element should be added. All Vector elements with index numbers greater than or equal to index are moved to make room for the new element. The following example builds a Vector of Integer values and uses insertElementAt to fill in a gap:

Vector vector1 = new Vector();
vector1.addElement(new Integer(10));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(12));
vector1.addElement(new Integer(14));
vector1.addElement(new Integer(15));

vector1.insertElementAt(new Integer(13), 3);

Graphics g = getGraphics();
g.drawString(vector1.toString(), 15, 15);

obj is the object to add to the vector.

index is the zero-based index at which the object is to be inserted.

ArrayIndexOutOfBoundsException is thrown if the specified index is invalid.

isEmpty

Vector

public final boolean isEmpty()

This method is used to determine whether the Vector contains any elements.

true if the Vector has no elements; false, otherwise.

lastElement

Vector

public final synchronized Object lastElement()

This method retrieves the last element in the Vector. If the Vector is empty, an exception is thrown. As an example of lastElement, the following will display "third string":

Vector myVector = new Vector();
myVector.addElement(new String("first string"));
myVector.addElement(new String("second string"));
myVector.addElement(new String("third string"));

Graphics g = getGraphics();
g.drawString((String)myVector.lastElement(), 15, 15);

The element at the specified zero-based index.

NoSuchElementException is thrown if the Vector is empty.

lastIndexOf

Vector

public final int lastIndexOf(Object elem)

This method searches the Vector and returns the zero-based index number of the last matching object. The following example creates a vector and then finds the last element number (4) that matches the Integer 11 element:

Vector vector1 = new Vector();
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(21));
vector1.addElement(new Integer(31));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(21));

int index = vector1.lastIndexOf(new Integer(11));

Graphics g = getGraphics();
g.drawString("Item found at index " + index, 15, 15);

Because this method always starts searching from the last element in the Vector, it can be used only to find the last matching index number. For other methods that can be used to find items, see indexOf(Object elem, int index), lastIndexOf(Object elem), and indexOf(Object elem, int index).

elem is the element for which you want to find the index.

The element number of the last element that matches elem; if no match is found, -1 is returned.

lastIndexOf

Vector

public final synchronized int lastIndexOf(Object elem, int index)

This method finds the last element in the Vector that matches elem starting at the element given by index. It is very useful for traversing a Vector backward, searching for all elements matching a specific object. The following example demonstrates this by searching from the end of the Vector to the front:

Vector vector1 = new Vector();
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(21));
vector1.addElement(new Integer(31));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(21));

int index = vector1.size() - 1; // start on last element
int itemsFound = 0;
Integer findMe = new Integer(11);
Graphics g = getGraphics();
while (index != -1) {
    index = vector1.lastIndexOf(findMe, index);
    if (index != -1) {
        itemsFound++;
        g.drawString("Matched element " + index, 15, itemsFound * 15);
    }
}
g.drawString("Matching items: " + itemsFound, 15, itemsFound*15 + 15);

elem is the element for which you want to find the index.

index is the index number at which to start the search.

The element number of the last element that matches elem; if no match is found, -1 is returned.

RemoveAllElements

Vector

public final synchronized void removeAllElements()

This method can be used to remove all elements from the Vector.

RemoveElement

Vector

public final synchronized boolean removeElement(Object obj)

This method can be used to remove a specific element from the Vector. Only the first element that matches obj is removed. In order to remove all matching elements, create a loop as shown in the following code:

Vector vector1 = new Vector();
vector1.addElement(new String("Jay"));
vector1.addElement(new String("Mark"));
vector1.addElement(new String("Ted"));
vector1.addElement(new String("Ron"));
vector1.addElement(new String("Ted"));

int removed = 0;
while (vector1.removeElement(new String("Ted")))
    removed++;

obj is the object to remove.

True if the element was found and deleted; false, otherwise.

removeElementAt

Vector

public final synchronized void removeElementAt(int index)

This method removes the element at the specified zero-based index. For example, the following code inserts duplicate elements with a value of 13. To remove the one stored in index 3, you would use the following:

Vector vector1 = new Vector();
vector1.addElement(new Integer(10));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(12));
vector1.addElement(new Integer(13));
vector1.addElement(new Integer(13));
vector1.addElement(new Integer(14));
vector1.addElement(new Integer(15));

vector1.removeElementAt(3);

Graphics g = getGraphics();
g.drawString(vector1.toString(), 15, 15);

index is the index number of the element to remove from the vector.

ArrayIndexOutOfBoundsException is thrown if the specified index is invalid.

setElementAt

Vector

public final synchronized void setElementAt(Object obj, int index)

This method replaces an element in the Vector with another element. The following example replaces the element at index 3 with the Integer 13:

Vector vector1 = new Vector();
vector1.addElement(new Integer(10));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(12));
vector1.addElement(new Integer(23));
vector1.addElement(new Integer(14));
vector1.addElement(new Integer(15));

vector1.setElementAt(new Integer(13), 3);

obj is the object to be placed in the Vector.

index is the index number of the element to be replaced.

ArrayIndexOutOfBoundsException is thrown if the specified index is invalid.

setSize

Vector

public final synchronized void setSize(int newSize)

This method sets the size of the Vector. If the specified size makes the Vector too small to hold its current elements, elements from the end of the Vector are removed. If the new size is larger than the current size, empty elements are added at the end of the Vector. For example, the following code sets the Vector to a size of three and removes two elements from the end of the Vector:

Vector vector1 = new Vector(5);
vector1.addElement(new Integer(10));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(12));
vector1.addElement(new Integer(13));
vector1.addElement(new Integer(14));

// vector = [10, 11, 12, 13, 14]
vector1.setSize(3);
// vector = [10, 11, 12]

newSize is the desired size of the Vector.

size

Vector

public final int size()

The method returns the number of elements currently in the Vector. For example, the variable qty in the following code will equal 3:

Vector myVector = new Vector(10);
myVector.addElement(new Integer(1));
myVector.addElement(new Integer(2));
myVector.addElement(new Integer(3));
int qty = myVector.size();                // will equal 3

The number of elements in the Vector.

ToString

Vector

public final synchronized String toString()

This method overrides the toString method in Object and formats the contents of the Vector as a string. For example, the following code will display [10, 11, 12, 13]:

Vector vector1 = new Vector(5);
vector1.addElement(new Integer(10));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(12));
vector1.addElement(new Integer(13));

Graphics g = getGraphics();
g.drawString("Contents are "+ vector1.toString(), 15, 15);

A string representation of the Vector.

TrimToSize

Vector

public final synchronized void trimToSize()

This method removes any excess capacity from the Vector by resizing it to hold only the quantity of elements it currently holds. If new items are added, the size of the Vector will be increased. In the following example, originalCapacity will equal 10, and newCapacity will equal 4:

Vector vector1 = new Vector(10);
vector1.addElement(new Integer(10));
vector1.addElement(new Integer(11));
vector1.addElement(new Integer(12));
vector1.addElement(new Integer(13));

int originalCapacity = vector1.capacity();
vector1.trimToSize();
int newCapacity = vector1.capacity();

EmptyStackException

RuntimeException

The class java.util.EmptyStackException is thrown to indicate that a Stack is empty. It can be thrown by the following methods:

The non-private interface of the class is shown in Listing 34.13.


Listing 34.13. The exception EmptyStackException.
public class EmptyStackException extends RuntimeException {
  // public constructors
     public EmptyStackException();
}

EmptyStackException

EmptyStackException

public EmptyStackException();

This constructor creates a new instance of the exception without a detail message.

NoSuchElementException

RuntimeException

The class java.util.NoSuchElementException is thrown to indicate either of the following conditions:

This exception can be thrown by the following methods:

The non-private interface of the class is shown in Listing 34.14.


Listing 34.14. The exception NoSuchElementException.
public class NoSuchElementException() extends RuntimeException {
  // public constructors
     public NoSuchElementException();
}

NoSuchElementException

NoSuchElementException

public NoSuchElementException();

This constructor creates a new instance of the exception without a detail message.

NoSuchElementException

NoSuchElementException

public NoSuchElementException(String s);

This constructor creates a new instance of the exception using the specified detail message. To retrieve the contents of the detail after an exception occurs, use code similar to the following:

try {
    // exception producing code
}
catch (NoSuchElementException e) {
    System.out.println("Exception: " + e.getMessage());