java.util.* : Stack , StringTokenizer , Random , Date Vector and Hashtable classes

The java.util package defines some very useful classes. util is not strictly a utility package. A significant part of the language requires the use of this class.

Most frequently used classes will be explained in the succeeding pages.

Stack

This class is a last-in-first-out stack of objects. Typical push() and pop() methods exist in the stack.

StringTokenizer

This class breaks up a given string into tokens separated by any of the given delimiters. This class implements the Enumeration interface so hasMoreElements() and nextElement() methods can be used.

Code example with StringTokenizer

Random

This is a pseudo-random number generator. This class can give random double, float, long or ints. It can create a gaussian distribution with a mean of 0 and a standard deviation of 1.

java.util.Date

The Date class lets you create a Date by specifying the number of milliseconds since midnight GMT, January 1st 1970. You can also create a Date by giving the year, month, date and optionally, the hour, minute and second. Year is specified by number of years since 1900. Date has several different constructors.

Using java.util.Date

Date _date = new Date();

System.out.println(_date.getMonth()); // prints a 3 for April, 0 for January

System.out.println(_date.toLocaleSting()); // Mon Apr 22 12:40:56 1996

The current Date class does not have methods that return “Jan” or “Monday” or any string names. It is a good idea to extend the Date class and create methods that will do this for you.

java.util.Enumeration

Enumeration is returned by Vector and Hashtable methods, It is also implemented in StringTokenizer. An Enumeration is a list of objects and is used to iterate through the list.

Using java.util.Enumeration

// Assume Vector _vector has been filled with strings. 

String string; Enumeration enum = _vector.elements(); while (enum.hasMoreElements()) { string = (String)enum.nextElement(); // Cast is needed !!! System.out.println(string); }
        // Hashtable table includes multiple key-values
        for (Enumeration keys = table.keys(); keys.hasMoreElements();){
            String key = (String)keys.nextElement();
            Object o = table.get(key);
            if(o instanceof String) {
                resultString += " \n";
            } else if( o instanceof Hashtable) {
                resultString += toXML((Hashtable)o);
            }
        }

java.util.Vector and java.util.Hashtable are basic Java storage classes. They store objects, not primitive types. In the three lines example below we show how to create a Vector an how to add alements to the storage.
....
        Object x = new Object();
	Vector v = new Vector(); 
	v.addElement(new Integer(y)); 
	v.addElement(x); // we can place different objects into a vector
....

Vector works like an array of objects that can be different nature. Vector is preferable to use when number of objects is unknown. Vector methods automatically allocate additional memory when needed.

Vector V = new Vector();

V.addElement(new Integer(y));

V.addElement(X);

Example of Vector usage


......

private final int CC_SIZE = 10;

Vector _vector = new Vector(CC_SIZE);

for (int x = 0; x <= CC_SIZE; x += 2)

_vector.addElement(new Integer(x));

for (int x = 0; x < _vector.size(); x++)

System.out.println(_vector.elementAt(x));

System.out.println(_vector);

System.out.println("Index of 7 = " + _vector.indexOf(new Integer(7));

System.out.println("Index of 6 = " + _vector.indexOf(new Integer(6));

......

java.util.Hashtable

USING HASHTABLE.  Hashtable is a class that is part of the core API
java.util.  It is used to efficiently store and look up key/element pairs.
Hashtable is extended from an abstract class called Dictionary, a name that
clearly describes its purpose.

To see how Hashtable might be used, consider an application that needs to
count how many times each line occurs in a file.  This technique could be
used in tabulating word frequencies, for example.  Using Hashtable, one way
of doing this is the following:

        import java.io.*;
        import java.util.*;
        
        public class hash {
                private static class countrec {
                        int count;
                };
                public static void main(String args[])
                {
                        try {
                                FileReader fr = new FileReader(args[0]);
                                BufferedReader br = new BufferedReader(fr);
                                Hashtable ht = new Hashtable();
                                String key = null;
                                while ((key = br.readLine()) != null) {
                                        countrec crec = (countrec)ht.get(key);
                                        if (crec == null) {
                                                crec = new countrec();
                                                crec.count = 1;
                                                ht.put(key, crec);
                                        }
                                        else {
                                                crec.count++;
                                        }
                                }
                                br.close();
                                Enumeration en = ht.keys();
                                while (en.hasMoreElements()) {
                                        String el = (String)en.nextElement();
                                        countrec crec = (countrec)ht.get(el);
                                        System.out.println(crec.count +
                                            " " + el);
                                }
                        }
                        catch (Throwable e) {
                                System.err.println(e);
                        }
                }
        }

There are several interesting points to note in the example.  The basic
operations of adding to a hash table, or looking up keys in it, are
implemented via the put and get methods.  The put method puts a key and
element pair into the table, while get looks up an element using its key
and returns the element.  Object.hashCode or an overriding hashCode method
in a subclass of Object is used to compute the actual hash value needed for
insertion into the hash table.

countrec is an example of an inner class, and is new feature in JDK(tm)
1.1.  It's a nested top-level class, meaning that it is available only
within the hash class that declares it.  countrec could be defined outside
of hash, or even in a separate file.  But defining it in the way shown here
offers the benefit of keeping it very localized, and not exposed to other
classes or applications.

Note also that get and put deal with Object references.  If you want to use
fundamental types like int or double with Hashtable, you will need to use
wrapper classes such as Integer or Double defined in java.lang.

--- Retrieving Results

Once all the lines have been read from the file and inserted into the hash
table, the next step is to retrieve the results, that is, the set of keys
and the associated elements that go with each key.  To do this, an
enumeration is retrieved using the keys method of Hashtable.  Enumeration
is an interface, and a class that implements it is guaranteed to define the
methods hasMoreElements and nextElement used for stepping through a list of
items.  In this example the items are keys from the hash table.  These are
stepped through in turn and the associated elements retrieved.

It's possible to tune the performance of a hash table by setting its
initial size and its load factor.  For example, the initial load factor is
0.75, meaning that if the table becomes more than 75 percent full, the
capacity will be increased via internal rehashing of the table.

A Hashtable maps keys to values. 
Any non-null object can be used as a key or as a value. 

To successfully store and retrieve objects from a hashtable, 
the objects used as keys must implement 
the hashCode method and the equalsmethod.

In the example below we use different shapes as objects and shape names as keys.

import java.util.Hashtable;
import java.util.Enumeration;
import java.util.Vector;

/**
 * This class is to demo Hashtable usage.
 * Hashtable is capable to store any object associated with another object.
 * The simpliest and most commonly used association is with the object name.
 * In this eiample we store Vector of different object-shapes with their names.
 * Each shape has its own name, for eiample "Line", "Rect".
 * Each shape inherits from class Shape.
 */
public class HashtableUsage
{
	private Hashtable _shapes;

	public HashLab(
		String[]	iShapeNames,
		Vector iShapes) throws ArrayIndeiOutOfBoundsEiception
	{
		_shapes = new Hashtable(iShapeNames.length);

		if (iShapes.size() != iShapeNames.length)
		{
			throw new ArrayIndeiOutOfBoundsEiception("\n" +
			  "iShapes size different than iShapeNames length \n" +
			  "iShapes.size() = " + iShapes.size() + "\n" +
			  "iShapeNames.length = " + iShapeNames.length);
		}
		for (int i = 0; i < iShapes.size(); i++)
		{
			_shapes.put(iShapeNames[i], (Shape)iShapes.elementAt(i));
		}
	}

/**
 * getShape() metod returns an object associated with the name from Hashtable
 *
 * @param iName name of the shape-object to get
 * @return aShape
 */
	public Shape getShape(String iName) {
		Shape aShape = _shapes.get(iName);
		return aShape;
	}
}

Back To Java School