Chapter  14

The Java Utility Package

by Debasis Samanta


CONTENTS

Introduction

The Package java.util contains miscellaneous utility classes, and related interfaces, and exceptions. It includes generic data structures like Dictionary, Hashtable, Stack, Vector, string manipulation, random number generation, system properties, notification and enumeration of data structures, and calender and date utilities.

The java.util package also contains the Observer interface and Observable class, which allow objects to notify one another when they change.

Following is the list of classes, interfaces, and exceptions which belong to this package.

	
	Classes
		Class BitSet  
		Class Date  
		Class Dictionary  
		Class Hashtable  
		Class Observable  
		Class Properties  
		Class Random  
		Class Stack  
		Class StringTokenizer  
		Class Vector  
	Interfaces
		Interface Enumeration  
		Interface Observer  
	Exceptions
		Class EmptyStackException  
		Class NoSuchElementException  

Class BitSet

This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are inded by nonnegative integers. Individual bits can be examined, set, or cleared. By default, all bits in the set initially have the value false. Every bit set has a current size, which is the number of bits currently in the bit set. Following is the whole class BitSet :
		public  final  class  java.util.BitSet extends  java.lang.Object  
		implements java.lang.Cloneable   
		{
				// 	Constructors
			public BitSet();
			//	Creates a new bit set. All bits are initially false. 	 
			public BitSet(int  nbits);
			//	Creates a bit set whose initial size is nbits, the specified number of bits. All bits are initially false. 	 

			 // 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);	 
		}

	All the mellthods are described in Table 3.1.

Table 3.1


Method

Description

and(BitSet set)

Performs a logical and of this target bit set with the argument bit set. This bit set is modified so that each bit in it has the value true if and only if it both initially had the value true and the corresponding bit in the bit set argument also had the value true.

clear(int bit)

Sets the bit specified by the index to false.

clone()

The clone of the bit set is another bit set that has exactly the same bits set to true as this bit set and the same current size.

equals(Object obj)

The result is true if and only if the argument is not null and is a Bitset object that has exactly the same set of bits set. The current sizes of the two bit sets are not compared, false otherwise.

get(int bit)

Returns the value of the bit with the specified index.

hashCode()

Returns a hash code value for this bit set.

Table 3.1(contd...)  

or(BitSet set)

Performs a logical or of this bit set with the bit set argument. This bit set is modified so that a bit in it has the value true if and only if it either already had the value true or the corresponding bit in the bit set argument has the value true.44

set(int bit)

Sets the bit specified by the index to true.

size()

Returns the number of bits currently in this bit set.

toString()

Returns a string representation of this bit set.

xor(BitSet set)

Performs a logical xor of this bit set with the bit set argument. This bit set is modified so that a bit in it has the value true if and only if one of the following statements holds:

The bit initially has the value true, and the corresponding bit in the argument has the value false.

The bit initially has the value false, and the corresponding bit in the argument has the value true.

Class Date

While the Date class is intended to reflect UTC (Coordinated Universal Time), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 x 60 x 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a "leap second." The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.

The class Date provides an abstraction of dates and times. Dates may be constructed from a year, month, date (day of month), hour, minute, and second. Those six components, as well as the day of the week, may be extracted from a date. Dates may also be compared and converted to a readable string form. A date is represented to a precision of one millisecond. As examples, To print today's date:

System.out.println("today = " + new Date());
To find out the day of the week for some particular date, for example, January 05, 1964 :
new Date(64, 0, 15).getDay();
Some computer standards are defined in terms of GMT (Greenwich Mean Time), which is equivalent to UT (Universal Time). GMT is the "civil" name for the standard; UT is the "scientific" name for the same standard. The distinction between UTC and UT is that UTC is based on an atomic clock and UT is based on astronomical observations, which for all practical purposes is an invisibly fine hair to split. Because the earth's rotation is not uniform-it slows down and speeds up in complicated ways-UT does not always flow uniformly. Leap seconds are introduced as needed into UTC so as to keep UTC within 0.9 seconds of UT1, which is a version of UT with certain corrections applied. There are other time and date systems as well; for example, the time scale used by GPS (the satellite-based Global Positioning System) is synchronized to UTC but is not adjusted for leap seconds.

In all methods of class Date that accept or return year, month, date, hours, minutes, and seconds values, the following representations are used :

  • A year y represented by the integer y - 1900.
  • A month is represented by an integer form 0 to 11; 0 is January, 1 is February, and so on; thus 11 is December.
  • A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
  • An hour is represented by an integer from 0 to 23. Thus the hour from midnight to 1 AM is hour 0, and the hour from noon to 1 PM is hour 12.
  • A minute is represented by an integer from 0 to 59 in the usual manner.
  • A second is represented by an integer from 0 to 60; the value 60 occurs only for leap seconds and even then only in Java implementations that actually track leap seconds correctly.

    In all cases, arguments given to methods for these purposes need not fall within the indicated ranges; for example, a date may be specified as January 32 and is interpreted as meaning February 1.

    	Let us see the class stucture for the above mentioned facts.
    
    	public  class  java.util.Date extends  java.lang.Object
    	{
    			// 	Constructors
    			public Date();
    			/*	Allocates a Date object and initializes it so that it represents the time at which it was allocated measured to the nearest millisecond. 	 
    			*/
    			public Date(int  year, int  month, int  date);
    			/*	Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments. 
    			*/	 
    			public Date(int  year, int  month, int  date,int  hrs, int  min);
    			/*	Allocates a Date object and initializes it so that it represents the specified hour and minute, local time, of the date specified by the year, month, and date arguments.
    			*/
    			public Date(int  year, int  month, int  date,int  hrs, int  min, int  sec);
    			/*	Allocates a Date object and initializes it so that it represents the specified hour, minute, and second, local time of the date specified by the year, month, and date arguments.
    			*/
    			public Date(long  date); 
    			/*	Allocates a Date object and initializes it to represent the specified number of milliseconds since January 1, 1970, 00:00:00GMT.
    			*/
    			public Date(String  s);
    			/*	Allocates a Date object and initializes it that that it represents the date and time indicated by the string s, which is interpreted as if by the parse method.
    			*/
    				// Methods
    			public boolean after(Date  when); 
    			public boolean before(Date  when);	 
    			public boolean equals(Object  obj);	 
    			public int getDate();	 
    			public int getDay(); 
    			public int getHours();	 
    			public int getMinutes();	 
    			public int getMonth(); 
    			public int getSeconds();	 
    			public long getTime(); 
    			public int getTimezoneOffset(); 
    			public int getYear();	 
    			public int hashCode();	 
    			public static long parse(String  s); 
    			public void setDate(int  date);	 
    			public void setHours(int  hours);	 
    			public void setMinutes(int  minutes); 
    			public void setMonth(int  month); 
    			public void setSeconds(int  seconds);	 
    			public void setTime(long  time);	 
    			public void setYear(int  year);	 
    			public String toGMTString();	 
    			public String toLocaleString();	 
    			public String toString();	 
    			public static long UTC(int  year, int  month, int  date,int  hrs, int  min, int  sec);
    		}
    
    	The methods are listed in Table 3.2.
    

    Table 3.2


    Method

    Description

    after(Date when)

    Returns: true if this date is after the argument date; false otherwise.

    before(Date when)

    Returns: true if this date is before the argument date; false otherwise.

    equals(Object obj)

    The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object .

    getDate()

    Returns: the day of the month represented by this date. The value returned is between 1 and 31.

    getDay()

    Returns: the day of the week represented by this date. The value returned is between 0 and 6, where 0 represents Sunday.

    getHours()

    Returns: the hour represented by this date. The value returned is between 0 and 23, where 0 represents midnight.

    getMinutes()

    Returns: the number of minutes past the hour represented by this date. The value returned is between 0 and 59.

    getMonth()

    Returns: the month represented by this date. The value returned is between 0 and 11, with the value 0 representing January.

    getSeconds()

    Returns: the number of seconds past the minute represented by this date. The value returned is between 0 and 60. The value 60 can only occur on those Java Virtual Machines that take leap seconds into account.

    getTime()

    Returns: the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date.

    getTimezoneOffset()

    Determines the local time zone offset. The time zone noffset is the number of minutes that must be added to Greenwich Mean Time to give the local time zone.

    getYear()

    Returns: the year represented by this date, minus 1900.

    hashCode()

    Returns: a hash code value for this object.


    Table 3.2 (Contd..)

     

    parse(String s)

    Given a string representing a time, parse it and return the time value.

    This method recognizes most standard syntaxes. It accepts many syntaxes; in particular, it recognizes the IETF standard date syntax: "Sat, 12 Aug 1995 13:30:00 GMT". It also understands the continental US time zone abbreviations, but for general use, a timezone offset should be used: "Sat, 12 Aug 1995 13:30:00 GMT+0430" (4 hours, 30 minutes west of the Greenwich meridian). If no time zone is specified, the local time zone is assumed. GMT and UTC are considered equivalent.Þ777

    setDate(int date)

    Sets the day of the month of this date to the specified value.

    setHours(int hours)

    Sets the hour of this date to the specified value.

    setMinutes(int minutes)

    Sets the minutes of this date to the specified value.

    setMonth(int month)

    Sets the month of this date to the specified value.

    setSeconds(int seconds)

    Sets the seconds of this date to the specified value..

    setTime(long time)

    Sets this date to represent the specified number of milliseconds since January 1, 1970 00:00:00 GMT.

    setYear(int year)

    Sets the year of this date to be the specified value plus 1900.

    toGMTString()

    Creates a string representation of this date. The result is of the form :

    "12 Aug 1995 02:30:00 GMT"; the day of the month is always one or two digits. The other fields have exactly the width shown. The timezone is always given as "GMT".

    toLocaleString()

    Creates a string representation of this date is an implementation-dependent form.

    toString()

    Creates a canonical string representation of the date. The result is of the form :

    "Mon Jul 12 02:30:00 PDT 1998".

    UTC(int year, int month, int date, int hrs, int min, int sec)

    Determines the date and time based on the arguments. The arguments are interpreted in UTC, not in the local time zone.

    Class Dictionary

    The Dictionary class is the abstract parent of any class, such as Hashtable which maps keys to values. Any non-null object can be used as a key and as a value.

    	public  abstract  class  java.util.Dictionary extends  java.lang.Object   
    	{
    			// 	Constructors
    		public Dictionary();
    		//	The default constructor. 
    
    		// 	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(); 
    	}
    
     	Methods are described in Table 3.3.
    

    Table 3.3

     

    Method

    Description

    elements()

    Returns: An enumeration of the values in the dictionary.

    get(Object key)

    Returns: the value to which the key is mapped in this dictionary; null if the key is not mapped to any value is thise dictionary.

    isEmpty()

    Returns: true if this dictionary maps no keys to values; false otherwise.

    keys()

    Returns: An enumeration of the keys in this dictionary.

    put(Object key, Object value)

    Returns: the previous value to which the key was mapped in the dictionary, or null if the key did not have a previous mapping.

    remove(Object key)

    Removes the key (and its corresponding value) from this dictionary. This method does nothing if the key is not in this dictionary.

    size()

    Returns: the number of keys in this dictionary.

    Class Hashtable

    This class implements a hash table, which 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 hash table, the objects used as keys must implement the hashCode method and the equals method.

    An instance of Hashtable has two parameters that affect its efficiency: its capacity and its load factor. The load factor should be between 0.0 and 1.0. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method. Larger load factors use memory more efficiently, at the expense of larger expected time per lookup.

    If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

    		As an example, following is a code to create a hashtable of numbers. It uses the names of the numbers as keys :
    				Hashtable  numbers  =  new  Hashtable();
    				numbers.put("one",  new  Integer(1));
    				numbers.put("two",  new  Integer(2));
    				numbers.put("three",  new  Integer(3));
    		
    		To retrieve a number use the following code:
    
    				Integer  n  =  (Integer)numbers.get("two");
    				if  (n  !=  null)  {
    					System.out.println("two  =  "  +  n);
    				}
    
    		Now, let us see the class structure.
    public class java.util.Hashtable extends java.util.Dictionary implements java.lang.Cloneable { // Constructors public Hashtable(); // Constructs a new empty hashtable. public Hashtable(int initialCapacity); /* Constructs a new, empty hash table with the specified initial capacity. Throws : IllegalArgumentException, if the initial capacity is less than or equal to zero. */ public Hashtable(int initialCapacity, float loadFactor); /* Constructs a new, empty hashtable with the specified initial capacity and the specified load factor. Throws : IllegalArgumentException, if the initial capacity is less than or equal to zero, or if the load factor is less than or equal to zero. */ // Methods public void clear(); public Object clone(); public boolean contains(Object value); public boolean containsKey(Object key); public Enumeration elements(); public Object get(Object key); public boolean isEmpty(); public Enumeration keys(); public Object put(Object key, Object value); protected void rehash(); public Object remove(Object key); public int size(); public String toString(); } Methods are stated in Table 3.4.

    Table 3.4

    .

    Method

    Description

    clear()

    Clears this hash table so that it contains no keys.

    clone()

    Creates a shallow copy of this hash table. The keys and values themselves are not cloned.

    contains(Object value)

    Returns : true if some key maps to the value argument in this hash table; false otherwise. Throws : NullPointerException, If the value is null.

    containsKey(Object key)

    Returns: true if the specified object is a key in this hash table; false otherwise.

    elements()

    Returns: an enumeration.

    get(Object key)

    Returns: the value to which the key is mapped in this hash table; null if the key is not mapped to any value is this hash table.

    isEmpty()

    Returns : true if this hash table maps no keys to values; false otherwise.

    keys()

    Returns: an enumeration of the keys in this hash table.

    put(Object key, Object value)

    Returns : the previous value of of the specified key in this hash table, or null if it did not have one. Throws : NullPointerException, If the value is null.

    rehash()

    Rehashes the contents of the hash table into a hash table with a larger capacity. This method is called automatically when the number of keys in the hash table exceeds this hash table's capacity and load factor.

    remove(Object key)

    Removes the key (and its corresponding value) from this hash table. This method does nothing if the key is not in the hash table.

    size()

    Returns: the number of keys in this hash table.

    toString()

    Returns: a string representation of this hash table.

    Class Observable

    This class represents an observable object, or "data" in the model-view paradigm. It can be subclassed to represent an object that the application wants to have observed.

    An observable object can have one or more observers After an observerable instance changes, an application calling the Observerable's notifyObservers method causes all of its observers to be notified of the change by a call to their update method.

    	The class structure is as shown below :
    
    	public  class  java.util.Observable
        					extends  java.lang.Object  
    	{
            	// 	Constructors
        	public Observable();	
    		//	The default constructor. 
    
            	// 	Methods
        	public void addObserver(Observer  o);	 
        	protected void clearChanged();	 
        	public int countObservers();	 
        	public void deleteObserver(Observer  o);	 
        	public void deleteObservers();	 
        	public boolean hasChanged();	 
        	public void notifyObservers(); 
        	public void notifyObservers(Object  arg);	 
        	protected void setChanged();	 
    	}
    	
    	Methods are described in Table 3.5.
    
    

    Table 3.5

     

    Method

    Description

    addObserver(Observer o)

    Adds an observer to the set of observers for this object.

    clearChanged()

    Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change. This method is call automatically by the notifyObservers methods .

    countObservers()

    Returns: the number of observers of this object.

    deleteObserver(Observer o)

    Deletes an observer from the set of observers of this object.

    deleteObservers()

    Clears the observer list so that this object no longer has any observers.

    hasChanged()

    Determines if this object has changed. Returns: true if the setChanged method has been called more recently than the clearChanged method on this object; false otherwise.

    notifyObservers()

    If this object has changed, as indicated by the hasChanged method, then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed. Each observer has its update method called with two arguments: the observable object and null argument

    notifyObservers(Object arg)

    If this object has changed, as indicated by the hasChanged method. 12 then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed. Each observer has its update method called with two arguments: the observable object and the arg argument

    setChanged()

    Indicates that this object has changed.

    Class Properties

    The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and and its corresponding value in the property list is a string.

    A property list can contain another property list as its "defaults"; this second property list is searched if the property key is not found in the original property list.

    	public  class  java.util.Properties
    						extends  java.util.Hashtable  
    	{
    			// 	Member elements
    		protected Properties defaults;
    		//	A property list which contains contains default values for any keys not found in this property list. 	 
    
    			// 	Constructors
    		public Properties();	 
    		//	Creates an empty property list with no default values.
    		public Properties(Properties  defaults);
    		//	Creates an empty property list with the specified defaults. 	 
    
    			// 	Methods
    		public String getProperty(String  key);	 
    		public String getProperty(String  key, String  defaultValue);  
    		public void list(PrintStream  out);	 
    		public void load(InputStream  in);	 
    		public Enumeration propertyNames();	 
    		public void save(OutputStream  out, String  header);	 
    	}
    	Methods are listed in Table 3.6.
    

    Table 3.6

     

    Method

    Description

    getProperty(String key)

    Searches for the property with the specified key in this property list. Returns: the value in this property list with the specified key value. If the key is not found in this property list, the default property list and its defaults, recursively, are then checked. The method returns null if the property is not found.

    getProperty(String key, String defaultValue)

    Searches for the property with the specified key in this property list. Returns: the value in this property list with the specified key value. If the key is not found in this property list, the default property list, and its defaults, recursively, are then checked. The method returns the default value argument if the property is not found.

    list(PrintStream out)

    Prints this property list out to the specified output stream. This method is useful for debugging.

    load(InputStream in)

    Reads a property list from an input stream. Throws : IOException, if an error occurred when reading from the input stream.13

    propertyNames()

    Returns: An enumeration of all the keys in this property list, including the keys in the default property list.

    save(OutputStream out, String header)

    Stores this property list to the specified output stream. The string header is printed as a comment at the beginning of the stream.

    Class Random

    An instance of this class is used to generate a stream of pseudo-random numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula.

    If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

    Many applications will find the random method in class Math simpler to use.

    	public  class  java.util.Random extends  java.lang.Object   
    	{
    			// 	Constructors
    		public Random();
    		//	Creates a new random number generator. Its seed is initialized to a value based on the current time.	 
    		public Random(long  seed);	
    		//	Creates a new random number generator using a single long seed. 
    
    		// 	Methods
    		public double nextDouble();	 
    		public float nextFloat();	 
    		public double nextGaussian(); 
    		public int nextInt(); 
    		public long nextLong();	 
    		public void setSeed(long  seed); 
    	}
    
    	Table 3.7 is to list the methods in  this class.
    

    Table 3.7

    Method

    Description

    nextDouble()

    Returns: the next pseudorandom, uniformally distributed double value between 0.0 and 1.0 from this random number generator's sequence.

    nextFloat()

    Returns: the next pseudorandom, uniformally distributed float value between 0.0 and 1.0 from this random number generator's sequence.

    nextGaussian()

    Returns: the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.

    nextInt()

    Returns: the next pseudorandom, uniformally distributed int value from this random number generator's sequence.

    nextLong()

    Returns: the nextpseudorandom, uniformally distributed long value from this random number generator's sequence.

    setSeed(long seed)

    Sets the seed of this random number generator using a single long seed.

    Class Stack

    The Stack class represents a last-in-first-out (LIFO) stack of objects.

    	public  class  java.util.Stack extends  java.util.Vector   
    	{
            	// 	Constructors
        	public Stack(); 
    		//	Creates a new stack with no elements.
    
            	// 	Methods
        	public boolean empty();	 
        	public Object peek(); 
        	public Object pop();	 
        	public Object push(Object  item);	 
        	public int search(Object  o);	 
    	}
    	
    	Methods are shown in Table 3.8.
    

    Table 3.8


    Method

    Description

    empty()

    Returns: true if this stack is empty; false otherwise.

    peek()

    Looks at the object at the top of this stack without removing it from the stack.

    Throws : EmptyStackException, if this stack is empty.

    pop()

    Removes the object at the top of this stack and returns that object as the value of this function.

    Throws : EmptyStackException, if this stack is empty.

    push(Object item)

    Pushes an item onto the top of this stack.

    search(Object o)

    Determines if an object is on this stack. Returns: The distance from the top of the stack that at which the object is located at; the return value -1 indicates that the object is not on the stack.

    Class StringTokenizer

    The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, not does it recognize and skip comments.

    The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis.

    An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with the return Tokens flag having the value true or false:

    If the flag is false, delimiter characters merely serve to separate tokens. A token is a maximal sequence of consecutive characters that are delimiters.

    If the flag is true, delimiters characters are considered to be tokens. A token is either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters.

    	The following is one example of the use of the tokenizer. The code :
    
    	StringTokenizer  st  =  new  StringTokenizer("I love Java !");
    			while  (st.hasMoreTokens())  {
           				println(st.nextToken());
    			} 
    	Prints the following output  : 
    			I
    			love
    			java
    			!
    
    	The class is furnished below :
    	
    	public  class  java.util.StringTokenizer extends  java.lang.Object  
    	implements java.util.Enumeration   
    	{
    			// 	Constructors
    		public StringTokenizer(String  str); 
    		/*	Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set, which is " \t\n\r", the space character, the tab character, the newline character, and the carriage return character.
    		*/
    		public StringTokenizer(String  str, String  delim);	
    		/*	Constructs a string tokenizer for the specified string. The characters in the delim argument are the delimiters for separating tokens.
    		*/ 
    		public StringTokenizer(String  str, String  delim,  boolean  returnTokens);
    		/*	Constructs a string tokenizer for the specified string. The characters in the delim argument are the delimiters for separating tokens. If the returnTokens flag is true, then the delimiter characters are also returned as tokens. Each delimiter is returned as a string of length one. If the flag is false, the delimiter characters are skipped and only serve as separators between tokens.
    		*/
    
    			// 	Methods
    		public int countTokens();	 
    		public boolean hasMoreElements();	 
    		public boolean hasMoreTokens(); 
    		public Object nextElement();	 
    		public String nextToken(); 
    		public String nextToken(String  delim);	 
    	}
    
    	Methods are described in Table3.9.
    

    Table 3.9

     

    Method

    Description

    countTokens()

    Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

    Returns: the number of tokens remaining in the string using thie current delimiter set.

    hasMoreElements()

    This method returns the same value as the following has MoreTokens method. It exists so that this class can implement the enumeration interface.

    Returns: true if there are more tokens; false otherwise.

    hasMoreTokens()

    Returns: true if there are more tokens available from this tokenizer's string; false otherwise.

    nextElement()

    This method returns the same value as the nextToken method, except that its declared return value is Object rather than String.

    Throws : NoSuchElementException, if there are no more tokens in this tokenizer's string.

    nextToken()

    Returns: the next token from this string tokenizer.

    Throws : NoSuchElementException, if there are no more tokens in this tokenizer's string.

    nextToken(String delim)

    Gets the next token in this stringt tokenizer's string. The new delimiter set remains the default after this call. Throws : NoSuchElementException, if there are no more tokens in this string.

    Class Vector

    The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.

    Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.

    	The class Vector is stated below :
    
    	public  class  java.util.Vector extends  java.lang.Object   
    	implements java.lang.Cloneable   
    	{
            	// 	Member elements
        	protected int capacityIncrement;
    		/*	The amount by which the capacity of the vector is automatically incremented when its size becomes greater than its capacity. If the capacity is 0, the capacity of the vector is doubled each time it needs to grow.
     		*/
        	protected int elementCount;
    		//	The number of valid components in the vector. 	 
        	protected Object elementData[]; 
    		/*	The array buffer into which the components of the vector are stored. The length of this array buffer is the (current) capacity of the vector.
    		*/
            	// 	Constructors
        	public Vector();
    		//	Constructs an empty vector.
    		public Vector(int  initialCapacity);
    		//	Constructs an empty vector. Its initial capacity is the specified argument initialCapacity. 
        	public Vector(int  initialCapacity, int  capacityIncrement);
    		//	Constructs an empty vector with the specified capacity and the specified capacity increment.
    
            	// 	Methods
        	public final void addElement(Object  obj); 
        	public final int capacity();	 
        	public Object clone();	 
        	public final boolean contains(Object  elem); 
        	public final void copyInto(Object  anArray[]); 
        	public final Object elementAt(int  index); 
        	public final Enumeration elements(); 
        	public final void ensureCapacity(int  minCapacity); 
        	public final Object firstElement();	 
        	public final int indexOf(Object  elem);	 
        	public final int indexOf(Object  elem, int  index);	 
        	public final void insertElementAt(Object  obj, int  index);	 
        	public final boolean isEmpty(); 
        	public final Object lastElement();	 
        	public final int lastIndexOf(Object  elem);	 
        	public final int lastIndexOf(Object  elem, int  index);	 
        	public final void removeAllElements();	 
        	public final boolean removeElement(Object  obj);	 
        	public final void removeElementAt(int  index); 
        	public final void setElementAt(Object  obj, int  index);	 
        	public final void setSize(int  newSize); 
        	public final int size();	 
        	public final String toString(); 
        	public final void trimToSize();	 
    	}
    	
    	Methods are decribed in Table 3.10.
    		
    

    Table 3.10

     

    Method

    Description

    addElement(Object obj)

    Adds the specified component to the end of this vector, increasing its size by one. The capacity of this vector is increased if its size becomes greater than its capacity.

    capacity()

    Returns : the current capacity of this vector.

    clone()

    Returns : a clone of this vector.

    contains(Object elem)

    Returns : true if the specified object is an component in this vector; false otherwise.

    copyInto(Object anArray[])

    Copies the components of this vector into the specified array. The array must be big enough to hold all the objects in this vector.

    elementAt(int index)

    Returns : the component at the specified index.

    Throws : ArrayIndexOutOfBoundsException, if an invalid index was given.

    elements()

    Returns : an enumeration of the components of this vector.

    ensureCapacity(int minCapacity)

    Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.

    firstElement()

    Returns : the first component of this vector.

    Throws : NoSuchElementException, if this vector has no components.

    indexOf(Object elem)

    Returns : the index of the first occurrence of the argument in this vector; returns -1 if the object is not found.

    indexOf(Object elem, int index)

    Returns : the index of the first occurrence of the object argument in thisn vector at position index or later in the vector; returns -1 if the object is not found.

    Table 3.10 (Contd..)

     

    insertElementAt(Object obj, int index)

    Inserts the specified object as an component in this vector at the specified index. Each component in this vector with an index greater or equal to the specified index is shifted upward to have an index one greater than the value it had previously. The index must be a value greater than or equal to 0 and less than or equal to the current size of the vector.

    Throws : ArrayIndexOutOfBoundsException, If the index was invalid.

    isEmpty()

    Returns : true if this vector has no components; false otherwise.

    lastElement()

    Returns : the last component of the vector.

    Throws : NoSuchElementException, If this vector is empty.

    lastIndexOf(Object elem)

    Returns : the index of the last occurrence of the argument in this vector; returns -1 if the object is not found.

    lastIndexOf(Object elem, int index)

    Searches backwards for the specified object, starting from the specified index and returns an index to it.

    Returns : the index of the last occurrence of the object argument in this vector at position less than index in the vector; returns -1 if the object is not found.

    removeAllElements()

    Removes all components from this vector and sets its size to zero.

    removeElement(Object obj)

    Removes the first occurrence of the argument from this vector. If the object is found in this vector, each component in the vector with an index greater or equal to the object's index is shifted downward to have an index one smaller than the value it had previously.

    Returns: true if the argument was a component of this vector; false otherwise.

    removeElementAt(int index)

    Deletes the component at the specified index. Each component in this vector with an index greater or equal to the specified index is shifted downward to have an index one smaller than the value it had previously.

    Throws : ArrayIndexOutOfBoundsException, if the index was invalid.

    setElementAt(Object obj, int index)

    Sets the component at the specified index of this vector to be the specified object. The previous component at that position is discarded.

    Throws : ArrayIndexOutOfBoundsException, if the index was invalid.

    setSize(int newSize)

    Sets the size of this vector. If the new size is greater than the current size, new null items are added to the end of the vector. If the new size is less than the current size, all components at index newSize and greater are discarded.

    size()

    Returns : the number of components in this vector.

    toString()

    Creates a string representation of this vector.

    Returns : a string representation of this vector.

    trimToSize()

    Trims the capacity of this vector to be the vector's current size . An application can use this operation to minimize the storage of a vector.

    Interface Enumeration

    An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series. For example, to print all elements of a Vector v , the code :

    	for  (Enumeration  e  =  v.elements();  e.hasMoreElements();)  
    	{        			System.out.println(e.nextElement());
    	}  
    

    Methods are provided to enumerate through the elements of a vector, the keys of a hash table , and the values in a hash table. Enumerations are also used to specify the input streams to a SequenceInputStream.

    public interface java.util.Enumeration { // Methods public abstract boolean hasMoreElements(); // Returns : true if this enumeration contains more elements; false otherwise. public abstract Object nextElement(); /* Returns : the next element of this enumeration. Throws : NoSuchElementException, if the element not found. */ }

    Interface Observer

    A class can implement the Observer interface when it wants to be informed if observable objects changes.

    	public  interface  java.util.Observer
    	{
            	// 	Methods
        	public abstract void update(Observable  o, Object  arg);
    		/*	This method is called whenever the observed object is changed. An application calls an observable object's notifyObservers method  to have all the object's observers notified of the change.
    		*/ 	 
    	}
    

    Class EmptyStackException

    Thrown by methods in the Stack class to indicate that the stack is empty.

    	public  class  java.util.EmptyStackException extends  java.lang.RuntimeException{
            	// 	Constructors
        	public EmptyStackException();
    		//	Constructs a new EmptyStackException with no detail message. 	
    	}
    

    Class NoSuchElementException

    Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

    	public  class  java.util.NoSuchElementException extends  java.lang.RuntimeException   
    	{
            	// 	Constructors
        public NoSuchElementException();
    		//	Constructs a NoSuchElementException with no detail message.
     	public NoSuchElementException(String  s);
    		//	Constructs a NoSuchElementException with the specified detail message. 	 
    	}