Wednesday 22 March 2017

StringTokenizer, BitSet & Date - Java Tutorials

StringTokenizer

The processing of text often consists of parsing a formatted input string. Parsing is the division of text into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic meaning. The StringTokenizer class provides the first step in this parsing process, often called the lexer (lexical analyzer) or scanner. StringTokenizer implements the Enumeration interface. Therefore, given an input string, you can enumerate the individual tokens contained in it using StringTokenizer.

To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters are characters that separate tokens. Each character in the delimiters string is considered a valid delimiter—for example, “,;:” sets the delimiters to a comma, semicolon, and colon. The default set of delimiters consists of the whitespace characters: space, tab, newline, and carriage return.

The StringTokenizer constructors are shown here:

      StringTokenizer(String str)
      StringTokenizer(String str, String delimiters)
      StringTokenizer(String str, String delimiters, boolean delimAsToken)

In all versions, str is the string that will be tokenized. In the first version, the default delimiters are used. In the second and third versions, delimiters is a string that specifies the delimiters. In the third version, if delimAsToken is true, then the delimiters are also returned as tokens when the string is parsed. Otherwise, the delimiters are not returned. Delimiters are not returned as tokens by the first two forms.

Once you have created a StringTokenizer object, the nextToken( ) method is used to extract consecutive tokens. The hasMoreTokens( ) method returns true while there are more tokens to be extracted. Since StringTokenizer implements Enumeration, the hasMoreElements( ) and nextElement( ) methods are also implemented, and they act the same as hasMoreTokens( ) and nextToken( ), respectively.

Here is an example that creates a StringTokenizer to parse “key=value” pairs. Consecutive sets of “key=value” pairs are separated by a semicolon.

  // Demonstrate StringTokenizer.
  import java.util.StringTokenizer;

  class STDemo {
    static String in = "title=Java: The Complete Reference;" +
      "author=Schildt;" +
      "publisher=Osborne/McGraw-Hill;" +
      "copyright=2002";

    public static void main(String args[]) {
      StringTokenizer st = new StringTokenizer(in, "=;");

      while(st.hasMoreTokens()) {
        String key = st.nextToken();
        String val = st.nextToken();
        System.out.println(key + "\t" + val);
      }
    }
  }


The Methods Defined by StringTokenizer

int countTokens( ):  Using the current set of delimiters, the method determines the number of tokens left to be parsed and returns the result.

boolean hasMoreElements( ):  Returns true if one or more tokens remain in the string and returns false if there are none.

boolean hasMoreTokens( ):  Returns true if one or more tokens remain in the string and returns false if there are none.

Object nextElement( ):  Returns the next token as an Object.

String nextToken( ):  Returns the next token as a String.

String nextToken(String delimiters):  Returns the next token as a String and sets the delimiters string to that specified by delimiters.


The output from this program is shown here:

  title Java: The Complete Reference
  author Schildt
  publisher Osborne/McGraw-Hill
  copyright 2002




BitSet

A BitSet class creates a special type of array that holds bit values. This array can increase in size as needed. This makes it similar to a vector of bits. The BitSet constructors are shown here:

      BitSet( )
      BitSet(int size)

The first version creates a default object. The second version allows you to specify its initial size (that is, the number of bits that it can hold). All bits are initialized to zero.


The Methods Defined by BitSet

void and(BitSet bitSet):  ANDs the contents of the invoking BitSet object with those specified by bitSet. The result is placed into the invoking object.

void andNot(BitSet bitSet):  For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared. (Added by Java 2)

int cardinality( ):  Returns the number of set bits in the invoking object. (Added by Java 2, version 1.4)

void clear( ):  Zeros all bits. (Added by Java 2, version 1.4)

void clear(int index):  Zeros the bit specified by index.

void clear(int startIndex, int endIndex):  Zeros the bits from startIndex to endIndex–1. (Added by Java 2, version 1.4)

Object clone( ):  Duplicates the invoking BitSet object.

boolean equals(Object bitSet):  Returns true if the invoking bit set is equivalent to the one passed in bitSet. Otherwise, the method returns false.

void flip(int index):  Reverses the bit specified by index. (Added by Java 2, version 1.4)

void flip(int startIndex, int endIndex):  Reverses the bits from startIndex to endIndex–1. (Added by Java 2, version 1.4)

boolean get(int index):  Returns the current state of the bit at the specified index.

BitSet get(int startIndex, int endIndex):  Returns a BitSet that consists of the bits from startIndex to endIndex–1. The invoking object is not changed. (Added by Java 2, version 1.4)

int hashCode( ):  Returns the hash code for the invoking object.

boolean intersects(BitSet bitSet):  Returns true if at least one pair of corresponding bits within the invoking object and bitSet are 1. (Added by Java 2, version 1.4)

boolean isEmpty( ):  Returns true if all bits in the invoking object are zero. (Added by Java 2, version 1.4)

int length( ):  Returns the number of bits required to hold the contents of the invoking BitSet. This value is determined by the location of the last 1 bit. (Added by Java 2)

int nextClearBit(int startIndex):  Returns the index of the next cleared bit, (that is, the next zero bit), starting from the index specified by startIndex. (Added by Java 2, version 1.4)

int nextSetBit(int startIndex):  Returns the index of the next set bit (that is, the next 1 bit), starting from the index specified by startIndex. If no bit is set, –1 is returned. (Added by Java 2, version 1.4)

void or(BitSet bitSet):  ORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed into the invoking object.

void set(int index):  Sets the bit specified by index.

void set(int index, boolean v):  Sets the bit specified by index to the value passed in v. true sets the bit, false clears the bit. (Added by Java 2, version 1.4)

void set(int startIndex, int endIndex):  Sets the bits from startIndex to endIndex–1. (Added by Java 2, version 1.4)

void set(int startIndex, int endIndex, boolean v):  Sets the bits from startIndex to endIndex–1, to the value passed in v. true sets the bits, false clears the bits. (Added by Java 2, version 1.4)

int size( ):  Returns the number of bits in the invoking BitSet object.

String toString( ):  Returns the string equivalent of the invoking BitSet object.

void xor(BitSet bitSet):  XORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed into the invoking object.


Here is an example that demonstrates BitSet:

  // BitSet Demonstration.
  import java.util.BitSet;

  class BitSetDemo {
    public static void main(String args[]) {
      BitSet bits1 = new BitSet(16);
      BitSet bits2 = new BitSet(16);

      // set some bits
      for(int i=0; i<16; i++) {
        if((i%2) == 0) bits1.set(i);
        if((i%5) != 0) bits2.set(i);
      }

      System.out.println("Initial pattern in bits1: ");
      System.out.println(bits1);
      System.out.println("\nInitial pattern in bits2: ");
      System.out.println(bits2);

      // AND bits
      bits2.and(bits1);
      System.out.println("\nbits2 AND bits1: ");
      System.out.println(bits2);

      // OR bits
      bits2.or(bits1);
      System.out.println("\nbits2 OR bits1: ");
      System.out.println(bits2);

      // XOR bits
      bits2.xor(bits1);
      System.out.println("\nbits2 XOR bits1: ");
      System.out.println(bits2);
    }
  }

The output from this program is shown here. When toString( ) converts a BitSet object to its string equivalent, each set bit is represented by its bit position. Cleared bits are not shown.

  Initial pattern in bits1:
  {0, 2, 4, 6, 8, 10, 12, 14}

  Initial pattern in bits2:
  {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}

  bits2 AND bits1:
  {2, 4, 6, 8, 12, 14}

  bits2 OR bits1:
  {0, 2, 4, 6, 8, 10, 12, 14}

  bits2 XOR bits1:
  {}




Date

The Date class encapsulates the current date and time. Before beginning our examination of Date, it is important to point out that it has changed substantially from its original version defined by Java 1.0. When Java 1.1 was released, many of the functions carried out by the original Date class were moved into the Calendar and DateFormat classes, and as a result, many of the original 1.0 Date methods were deprecated. Java 2 added a few new methods to the time and date classes, but otherwise implemented them in the same form as did 1.1. Since the deprecated 1.0 methods should not be used for new code, they are not described here.

Date supports the following constructors:

      Date( )
      Date(long millisec)

The first constructor initializes the object with the current date and time. The second constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970. The nondeprecated methods defined by Date are shown in Table 16-3. With the advent of Java 2, Date also implements the Comparable interface.


The Nondeprecated Methods Defined by Date

boolean after(Date date):  Returns true if the invoking Date object contains a date that is later than the one specified by date. Otherwise, it returns false.

boolean before(Date date):  Returns true if the invoking Date object contains a date that is earlier than the one specified by date. Otherwise, it returns false.

Object clone( ):  Duplicates the invoking Date object.

int compareTo(Date date):  Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date. (Added by Java 2)

int compareTo(Object obj):  Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException. (Added by Java 2)

boolean equals(Object date):  Returns true if the invoking Date object contains the same time and date as the one specified by date. Otherwise, it returns false.

long getTime( ):  Returns the number of milliseconds that have elapsed since January 1, 1970.

int hashCode( ):  Returns a hash code for the invoking object.

void setTime(long time):  Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970.

String toString( ):  Converts the invoking Date object into a string and returns the result.


As you can see by examining Table 16-3, the Date features do not allow you to obtain the individual components of the date or time. As the following program demonstrates, you can only obtain the date and time in terms of milliseconds or in its default string representation as returned by toString( ). To obtain more-detailed information about the date and time, you will use the Calendar class.

  // Show date and time using only Date methods.
  import java.util.Date;

  class DateDemo {
    public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();

      // display time and date using toString()
      System.out.println(date);

      // Display number of milliseconds since midnight, January 
                                                        1, 1970 GMT
      long msec = date.getTime();
      System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + 
                         msec);
    }
  }

Sample output is shown here:

  Mon Apr 22 09:51:52 CDT 2002
  Milliseconds since Jan. 1, 1970 GMT = 1019487112894


Date Comparison

There are three ways to compare two Date objects. First, you can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values. Second, you can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true. Finally, you can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.

The Legacy Classes and Interfaces - Java Tutorials ( Page - 3 of 3 )

Properties

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String. The Properties class is used by many other Java classes. For example, it is the type of object returned by System.getProperties( ) when obtaining environmental values.

Properties defines the following instance variable:

      Properties defaults;

This variable holds a default property list associated with a Properties object. Properties defines these constructors:

      Properties( )
      Properties(Properties propDefault)

The first version creates a Properties object that has no default values. The second creates an object that uses propDefault for its default values. In both cases, the property list is empty.

In addition to the methods that Properties inherits from Hashtable, Properties defines the methods listed in Table 15-14. Properties also contains one deprecated method: save( ). This was replaced by store( ) because save( ) did not handle errors correctly.


The Legacy Methods Defined by Properties

String getProperty(String key):  Returns the value associated with key. A null object is returned if key
is neither in the list nor in the default property list.

String getProperty(String key, String defaultProperty):  Returns the value associated with key. defaultProperty is returned if key is neither in the list nor in the default property list.

void list(PrintStream streamOut):  Sends the property list to the output stream linked to streamOut.

void list(PrintWriter streamOut):  Sends the property list to the output stream linked to streamOut.

void load(InputStream streamIn) throws IOException:  Inputs a property list from the input stream linked to streamIn.

Enumeration propertyNames( ):  Returns an enumeration of the keys. This includes those keys found in the default property list, too.

Object setProperty(String key, String value):  Associates value with key. Returns the previous value associated with key, or returns null if no such association exists. (Added by Java 2, for consistency.)

void store(OutputStream streamOut, String description):  After writing the string specified by description, the property list is written to the output stream linked to streamOut. (Added by Java 2.)


One useful capability of the Properties class is that you can specify a default property that will be returned if no value is associated with a certain key. For example, a default value can be specified along with the key in the getProperty( ) method—such as getProperty(“name”, “default value”). If the “name” value is not found, then “default value” is returned. When you construct a Properties object, you can pass another instance of Properties to be used as the default properties for the new instance. In this case, if you call getProperty(“foo”) on a given Properties object, and “foo” does not exist, Java looks for “foo” in the default Properties object. This allows for arbitrary nesting of levels of default properties.

The following example demonstrates Properties. It creates a property list in which the keys are the names of states and the values are the names of their capitals. Notice that the attempt to find the capital for Florida includes a default value.

  // Demonstrate a Property list.
  import java.util.*;

  class PropDemo {
    public static void main(String args[]) {
      Properties capitals = new Properties();
      Set states;
      String str;

      capitals.put("Illinois", "Springfield");
      capitals.put("Missouri", "Jefferson City");
      capitals.put("Washington", "Olympia");
      capitals.put("California", "Sacramento");
      capitals.put("Indiana", "Indianapolis");

      // Show all states and capitals in hashtable.
      states = capitals.keySet(); // get set-view of keys
      Iterator itr = states.iterator();

      while(itr.hasNext()) {
        str = (String) itr.next();
        System.out.println("The capital of " +
                           str + " is " +
                           capitals.getProperty(str)
                           + ".");
      }

      System.out.println();

      // look for state not in list -- specify default
      str = capitals.getProperty("Florida", "Not Found");
      System.out.println("The capital of Florida is "
                         + str + ".");
    }
  }

The output from this program is shown here:

  The capital of Missouri is Jefferson City.
  The capital of Illinois is Springfield.
  The capital of Indiana is Indianapolis.
  The capital of California is Sacramento.
  The capital of Washington is Olympia.

  The capital of Florida is Not Found.

Since Florida is not in the list, the default value is used.

Although it is perfectly valid to use a default value when you call getProperty( ), as the preceding example shows, there is a better way of handling default values for most applications of property lists. For greater flexibility, specify a default property list when constructing a Properties object. The default list will be searched if the desired key is not found in the main list. For example, the following is a slightly reworked version of the preceding program, with a default list of states specified. Now, when Florida is sought, it will be found in the default list:

  // Use a default property list.
  import java.util.*;

  class PropDemoDef {
    public static void main(String args[]) {
      Properties defList = new Properties();
      defList.put("Florida", "Tallahassee");
      defList.put("Wisconsin", "Madison");

      Properties capitals = new Properties(defList);
      Set states;
      String str;

      capitals.put("Illinois", "Springfield");
      capitals.put("Missouri", "Jefferson City");
      capitals.put("Washington", "Olympia");
      capitals.put("California", "Sacramento");
      capitals.put("Indiana", "Indianapolis");

      // Show all states and capitals in hashtable.
      states = capitals.keySet(); // get set-view of keys
      Iterator itr = states.iterator();

      while(itr.hasNext()) {
        str = (String) itr.next();
        System.out.println("The capital of " +
                           str + " is " +
                           capitals.getProperty(str)
                           + ".");
      }

      System.out.println();

      // Florida will now be found in the default list.
      str = capitals.getProperty("Florida");
      System.out.println("The capital of Florida is "
                         + str + ".");
    }
  }


Using store( ) and load( )

One of the most useful aspects of Properties is that the information contained in a Properties object can be easily stored to or loaded from disk with the store( ) and load( ) methods. At any time, you can write a Properties object to a stream or read it back. This makes property lists especially convenient for implementing simple databases. For example, the following program uses a property list to create a simple computerized telephone book that stores names and phone numbers. To find a person’s number, you enter his or her name. The program uses the store( ) and load( ) methods to store and retrieve the list. When the program executes, it first tries to load the list from a file called phonebook.dat. If this file exists, the list is loaded. You can then add to the list. If you do, the new list is saved when you terminate the program. Notice how little code is required to implement a small, but functional, computerized phone book.

  /* A simple telephone number database that uses
     a property list. */
  import java.io.*;
  import java.util.*;

  class Phonebook {
    public static void main(String args[])
      throws IOException
    {
      Properties ht = new Properties();
      BufferedReader br =
        new BufferedReader(new InputStreamReader(System.in));
      String name, number;
      FileInputStream fin = null;
      boolean changed = false;

      // Try to open phonebook.dat file.
      try {
        fin = new FileInputStream("phonebook.dat");
      } catch(FileNotFoundException e) {
        // ignore missing file
      }

      /* If phonebook file already exists,
         load existing telephone numbers. */
      try {
        if(fin != null) {
          ht.load(fin);
          fin.close();
        }
      } catch(IOException e) {
        System.out.println("Error reading file.");
      }

      // Let user enter new names and numbers.
      do {
        System.out.println("Enter new name" +
                           " ('quit' to stop): ");
        name = br.readLine();
        if(name.equals("quit")) continue;

        System.out.println("Enter number: ");
        number = br.readLine();

        ht.put(name, number);
        changed = true;
      } while(!name.equals("quit"));

      // If phone book data has changed, save it.
      if(changed) {
        FileOutputStream fout=new FileOutputStream("phonebook.dat");
        
        ht.store(fout, "Telephone Book");
        fout.close();
      }

      // Look up numbers given a name.
      do {
        System.out.println("Enter name to find" +
                           " ('quit' to quit): ");
        name = br.readLine();
        if(name.equals("quit")) continue;

        number = (String) ht.get(name);
        System.out.println(number);
      } while(!name.equals("quit"));
    }
  }


Collections Summary

The collections framework gives you, the programmer, a powerful set of well-engineered solutions to some of programming’s most common tasks. Consider using a collection the next time that you need to store and retrieve information. Remember, collections need not be reserved for only the “large jobs,” such as corporate databases, mailing lists, or inventory systems. They are also effective when applied to smaller jobs. For example, a TreeMap would make an excellent collection to hold the directory structure of a set of files. A TreeSet could be quite useful for storing project-management information. Frankly, the types of problems that will benefit from a collections-based solution are limited only by your imagination.

The Legacy Classes and Interfaces - Java Tutorials ( Page - 2 of 3 )

Stack

Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.

To put an object on the top of the stack, call push( ). To remove and return the top element, call pop( ). An EmptyStackException is thrown if you call pop( ) when the invoking stack is empty. You can use peek( ) to return, but not remove, the top object. The empty( ) method returns true if nothing is on the stack. The search( ) method determines whether an object exists on the stack, and returns the number of pops that are required to bring it to the top of the stack. Here is an example that creates a stack, pushes several Integer objects onto it, and then pops them off again:


The Methods Defined by Stack

boolean empty( ):  Returns true if the stack is empty, and returns false if the stack contains elements.

Object peek( ):  Returns the element on the top of the stack, but does not remove it.

Object pop( ):  Returns the element on the top of the stack, removing it in the process.

Object push(Object element):  Pushes element onto the stack. element is also returned.

int search(Object element):  Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, –1 is returned.


  // Demonstrate the Stack class.
  import java.util.*;

  class StackDemo {
    static void showpush(Stack st, int a) {
      st.push(new Integer(a));
      System.out.println("push(" + a + ")");
      System.out.println("stack: " + st);
    }

    static void showpop(Stack st) {
      System.out.print("pop -> ");
      Integer a = (Integer) st.pop();
      System.out.println(a);
      System.out.println("stack: " + st);
    }

    public static void main(String args[]) {
      Stack st = new Stack();

      System.out.println("stack: " + st);
      showpush(st, 42);
      showpush(st, 66);
      showpush(st, 99);
      showpop(st);
      showpop(st);
      showpop(st);
      try {
        showpop(st);
      } catch (EmptyStackException e) {
        System.out.println("empty stack");
      }
    }
  }

The following is the output produced by the program; notice how the exception handler for EmptyStackException is caught so that you can gracefully handle a stack underflow:

  stack: [ ]
  push(42)
  stack: [42]
  push(66)
  stack: [42, 66]
  push(99)
  stack: [42, 66, 99]
  pop -> 99
  stack: [42, 66]
  pop -> 66
  stack: [42]
  pop -> 42
  stack: [ ]
  pop -> empty stack


Dictionary

Dictionary is an abstract class that represents a key/value storage repository and operates much like Map. Given a key and value, you can store the value in a Dictionary object. Once the value is stored, you can retrieve it by using its key. Thus, like a map, a dictionary can be thought of as a list of key/value pairs. Although not actually deprecated by Java 2, Dictionary is classified as obsolete, because it is superceded by Map. However, Dictionary is still in use and thus is fully discussed here.

To add a key and a value, use the put( ) method. Use get( ) to retrieve the value of a given key. The keys and values can each be returned as an Enumeration by the keys( ) and elements( ) methods, respectively. The size( ) method returns the number of key/ value pairs stored in a dictionary, and isEmpty( ) returns true when the dictionary is empty. You can use the remove( ) method to delete a key/value pair.


The Abstract Methods Defined by Dictionary

Enumeration elements( ):  Returns an enumeration of the values contained in the dictionary.

Object get(Object key):  Returns the object that contains the value associated with key. If key is not in the dictionary, a null object is returned.

boolean isEmpty( ):  Returns true if the dictionary is empty, and returns false if it contains at least one key.

Enumeration keys( ):  Returns an enumeration of the keys contained in the dictionary.

Object put(Object key, Object value):  Inserts a key and its value into the dictionary. Returns null if key is not already in the dictionary; returns the previous value associated with key if key is already in the dictionary.

Object remove(Object key):  Removes key and its value. Returns the value associated with key. If key is not in the dictionary, a null is returned.

int size( ):  Returns the number of entries in the dictionary.


The Dictionary class is obsolete. You should implement the Map interface to obtain key/value storage functionality.


Hashtable

Hashtable was part of the original java.util and is a concrete implementation of a Dictionary. However, Java 2 reengineered Hashtable so that it also implements the Map interface. Thus, Hashtable is now integrated into the collections framework. It is similar to HashMap, but is synchronized.

Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

A hash table can only store objects that override the hashCode( ) and equals( ) methods that are defined by Object. The hashCode( ) method must compute and return the hash code for the object. Of course, equals( ) compares two objects. Fortunately, many of Java’s built-in classes already implement the hashCode( ) method. For example, the most common type of Hashtable uses a String object as the key. String implements both hashCode( ) and equals( ).

The Hashtable constructors are shown here:

      Hashtable( )
      Hashtable(int size)
      Hashtable(int size, float fillRatio)
      Hashtable(Map m)

The first version is the default constructor. The second version creates a hash table that has an initial size specified by size. The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how full the hash table can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded. If you do not specify a fill ratio, then 0.75 is used. Finally, the fourth version creates a hash table that is initialized with the elements in m. The capacity of the hash table is set to twice the number of elements in m. The default load factor of 0.75 is used. The fourth constructor was added by Java 2.


The Legacy Methods Defined by Hashtable

void clear( ):  Resets and empties the hash table.

Object clone( ):  Returns a duplicate of the invoking object.

boolean contains(Object value):  Returns true if some value equal to value exists within the hash table. Returns false if the value isn’t found.

boolean containsKey(Object key):  Returns true if some key equal to key exists within the hash table. Returns false if the key isn’t found.

boolean containsValue(Object value):  Returns true if some value equal to value exists within the hash table. Returns false if the value isn’t found. (A non-Map method added by Java 2, for consistency.)

Enumeration elements( ):  Returns an enumeration of the values contained in the hash table.

Object get(Object key):  Returns the object that contains the value associated with key. If key is not in the hash table, a null object is returned.

boolean isEmpty( ):  Returns true if the hash table is empty; returns false if it contains at least one key.

Enumeration keys( ):  Returns an enumeration of the keys contained in the hash table.

Object put(Object key, Object value):  Inserts a key and a value into the hash table. Returns null if key isn’t already in the hash table; returns the previous value associated with key if key is already in the hash table.

void rehash( ):  Increases the size of the hash table and rehashes all of its keys.

Object remove(Object key):  Removes key and its value. Returns the value associated with key. If key is not in the hash table, a null object is returned.

int size( ):  Returns the number of entries in the hash table.

String toString( ):  Returns the string equivalent of a hash table.


The following example reworks the bank account program, shown earlier, so that it uses a Hashtable to store the names of bank depositors and their current balances:

  // Demonstrate a Hashtable
  import java.util.*;
  class HTDemo {
    public static void main(String args[]) {
      Hashtable balance = new Hashtable();
      Enumeration names;
      String str;
      double bal;

      balance.put("John Doe", new Double(3434.34));
      balance.put("Tom Smith", new Double(123.22));
      balance.put("Jane Baker", new Double(1378.00));
      balance.put("Todd Hall", new Double(99.22));
      balance.put("Ralph Smith", new Double(-19.08));

      // Show all balances in hash table.
      names = balance.keys();
      while(names.hasMoreElements()) {
        str = (String) names.nextElement();
        System.out.println(str + ": " +
                           balance.get(str));
      }

      System.out.println();

      // Deposit 1,000 into John Doe's account
      bal = ((Double)balance.get("John Doe")).doubleValue();
      balance.put("John Doe", new Double(bal+1000));
      System.out.println("John Doe's new balance: " +
                         balance.get("John Doe"));
    }
  }

The output from this program is shown here:

  Todd Hall: 99.22
  Ralph Smith: -19.08
  John Doe: 3434.34
  Jane Baker: 1378.0
  Tom Smith: 123.22

  John Doe’s new balance: 4434.34

One important point: like the map classes, Hashtable does not directly support iterators. Thus, the preceding program uses an enumeration to display the contents of balance. However, you can obtain set-views of the hash table, which permits the use of iterators. To do so, you simply use one of the collection-view methods defined by Map, such as entrySet( ) or keySet( ). For example, you can obtain a set-view of the keys and iterate through them. Here is a reworked version of the program that shows this technique:

  // Use iterators with a Hashtable.
  import java.util.*;

  class HTDemo2 {
    public static void main(String args[]) {
      Hashtable balance = new Hashtable();
      String str;
      double bal;

      balance.put("John Doe", new Double(3434.34));
      balance.put("Tom Smith", new Double(123.22));
      balance.put("Jane Baker", new Double(1378.00));
      balance.put("Todd Hall", new Double(99.22));
      balance.put("Ralph Smith", new Double(-19.08));

      // show all balances in hashtable
      Set set = balance.keySet(); // get set-view of keys

      // get iterator
      Iterator itr = set.iterator();
      while(itr.hasNext()) {
        str = (String) itr.next();
        System.out.println(str + ": " +
                           balance.get(str));
      }

      System.out.println();

      // Deposit 1,000 into John Doe's account
      bal = ((Double)balance.get("John Doe")).doubleValue();
      balance.put("John Doe", new Double(bal+1000));
      System.out.println("John Doe's new balance: " +
                         balance.get("John Doe"));
    }
  }