Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Data Structures And Random Number Generation

java



+ Font mai mare | - Font mai mic



Data Structures And Random Number Generation

Java's utility classes provide a wide range of functionality for your applications. This chapter explains the utility classes for implementing data structures and random number generation. These classes form a part of the java.util package in the Java APIs. We will look at the data structure classes Dictionary, Hashtable, Vector, and Stack as well as the Properties class for maintaining the properties of objects. The Enumeration interface, which provides the methods necessary to enumerate a given set of elements from the vector or hash table is also covered, along with two additional classes: EmptyStackException and NoSuchElementException, which define the exceptions related to these data structures. The project developed at the end of this chapter is an Appointment Organizer application. It's a Java application that provides a user-interface to enter appointment details. Details about an appointment including the date and time are entered using text fields and a text area. Specifying the date and time provides a facility for retrieving the details. The classes discussed in this chapter will be used in this application.



Dictionary and Hashtable

Dictionary is an abstract class that maps keys to values in a table. It forms the super class of Hashtable. You should use hash tables when you want to store and retrieve elements efficiently. You can associate a key with each element you store, so that you can use the key to retrieve the element quickly. A function is used to map the key to a particular slot in the hash table. You should also note that there can be only one element for a given key in the hash table at a given time. As an example, consider the elements Arizona, California, New York, and Oregon. If you decide that the key for these elements is their first character, then mapping them to a hash table will result in the table shown in Figure 12-1(a). If a new element, North Carolina is listed after New York, then two elements will have the same key (N) resulting in a collision. In the Hashtable implementation of Java, when collisions occur, the new element replaces the old element. In our example, the element North Carolina will replace the element New York, resulting in the hash table shown in Figure 12-1(b).


Figure 12-1   Two hashtables (a) States with one string element (b) North Carolina replaces New York as both have the same key (N)

Note that we have implicitly assumed in our example that the size of the hash table is 26, mapping to the 26 characters in the English alphabet. This is called the capacity of the hash table. You can specify the capacity of the hash table when you create an instance of Hashtable. You can also specify the load factor. The load factor is the ratio of the number of elements in the hash table to the size of the hash table. In our example, the load factor is 4/26. Note that the load factor has a value between 0.0 and 1.0.

In Java, the Hashtable is a subclass of the Dictionary class. The Dictionary class encapsulates the characteristics of mapping keys to values. The Hashtable object expands automatically when it gets full. It will maintain the capacity such that the load factor of the table at any instance is at least the specified load factor. The elements can be any of the Objects in Java. So you can also have a list of strings as an element. Considering our example hash table of states, we can specify that elements with the same first character (key) form a growable list. So if we add North Carolina to the hash table, instead of replacing New York it will be added to the list of string with 'N' as the first character. Figure 12-2 shows the resulting table.


Figure 12-2   A hash table with the element being a list

Vector and Stack

The Vector class in Java represents an extensible array. You will often come across situations where you do not know the number of items in an array in advance. In such situations, you can use Vector. Imagine you were having a party to celebrate a promotion. You might arrange ten chairs in the living room to start. When an eleventh person arrives, you could fetch another chair, and continue adding one chair for every new guest, or you could bring three more chairs every time you run out of seats. (See Figure 12-3.) A Vector is like adding three chairs at a time, but the increased space is a memory unit, i.e., on demand for more space, new space gets allocated automatically. As more elements are stored in a Vector, the vector's size increases. You can specify it to increase by increments of size defined by capacityIncrement, a variable defined in the Vector class.


Figure 12-3   Providing seats for incoming guests (a) An eleventh guest needs a chair (b) Increase the number of chairs by five

A common data structure used in many applications is a stack. It is an ordered vector (Stack subclasses Vector) in which all insertions and deletions are made at one end, called the top. Consider four elements A, B, C, and D inserted in a stack in that order. Stack is a Last-In-First-Out structure, so A would be the bottommost element and D would be the topmost element, as shown in Figure 12-4. You can access B only after popping D and C off the stack. Stacks are useful when you want to access the most recently created items and only after using them will you get to use earlier items. Compilers typically use stacks to implement computations effectively. As a matter of fact, the Java interpreter is a stack-based interpreter compared to other register-based interpreters.


Figure 12-4   A stack of elements

Random Numbers

Random numbers are important in algorithms where you want to provide a variation in behavior or when you don't have a fixed option to consider. Assume you have five options to select from, namely: A, B, C, D, E. If you don't have any particular preference, you'll select one of them arbitrarily. Simulating this behavior in a computer program is achieved using random numbers. Pure random numbers are very difficult to generate, but a set of pseudo-random numbers can be generated by many available algorithms. Suppose you divide the interval between 0 and 1 into five equals units. You generate a random number and depending on which interval it occupies, one of the 5 elements is selected, as shown in Figure 12-5. For more accuracy you might want to generate double precision random numbers. Or you might be interested in integer random numbers. In Java, the Random class provides the methods to generate pseudo-random numbers. You can provide a seed to the generator so that it generates a repeatable set of pseudo-random numbers. This is necessary for users who repeat experiments and study the results at similar circumstances.


Figure 12-5   Random selection among 5 elements

Enumeration is a Java interface that provides a set of methods to enumerate or a method to count a set of objects. In the case of an array, you can access elements in the array by using the index numbers. But in the case of Vector or Stack, you don't have fixed indices. To index into these data structures, the Enumeration class is useful. It helps you to enumerate or count (and effectively index) the elements. The NoSuchElementException and StackEmptyException classes are defined to throw runtime exceptions while handling invalid elements in the data structure classes in Java.

Data Structure, Properties, and Random Class Summaries

Table 12-1 summarizes the classes and interface that help implement efficient algorithms using predefined data structures and utility class for random number generation.

Table 12-1 Class and interface summary for Data structure, Properties and Random classes


Class/Interface Name

Description


Dictionary

Maps keys to values and is the parent of Hashtable.

Hashtable

Encapsulates the features of a hash table to store and retrieve values efficiently.

Properties

Contains the persistent properties of the associated object.

Vector

Represents an extensible array, designed for space optimization.

Stack

Encapsulates the Last-In-First-Out(LIFO) stack of objects.

Enumeration

Interface that specifies methods to enumerate a set of objects.

Random

Generates pseudo-random numbers.

EmptyStackException

A Runtime exception that gets thrown when trying to pop out an object from an empty stack.

NoSuchElementException

A Runtime exception signaling an empty enumeration.

Dictionary

Purpose

An abstract class that maps keys to values and is the parent of Hashtable.

Syntax

public abstract class Dictionary extends Object

Description

Dictionary is an abstract class and the superclass of Hashtable. It maps keys to values. Any object can be used in a Dictionary as a key and/or a value. The Dictionary data structure improves search time for an element by use of its key. Operations on elements in a Dictonary can be carried out using its key. Figure 12-6 illustrates the inheritance relationship of class Dictionary.


Figure 12-6   Class diagram of Dictionary class

PackageName

java.util

Imports

import java.util.Dictionary;

Constructors

None.

Parameters

None.

Example

The class inventory applet, below, represents a basic inventory maintenance program. It uses a hash table for storing entries. Hashtable is a subclass of the abstract Dictionary class. The program for the inventory class is given in Listing 12-1.

Listing 12-1 inventory.java: Program illustrating use of hash table for inventory control

import java.util.*;

class inventory

protected void populate()

protected void addCheese()

protected void addCereal()

protected void listAll()

System.out.println(' Hash table contains the following
keys/items');
for (Enumeration e = ht.elements(), k = ht.keys();
e.hasMoreElements();)


protected void removeSoup()

protected void reset()

private void table()
protected void findChanges()



protected void getItem(String key)
public static void main(String args[])

elements()

ClassName

Dictionary

Purpose.

Provides an enumeration of the elements.

Syntax

public abstract Enumeration elements().

Parameters

None.

Description

The method returns an enumeration of the elements in Dictionary. This is an abstract method and should be overridden in its subclass. The enumeration that is returned can be used to fetch the elements sequentially.

Imports

java.utils.Dictionary

Returns

An Enumeration of elements. Return type is Enumeration.

See Also

The keys method in Dictionary class; Enumeration interface

Example

Refer to the method listAll() in class inventory in Listing 12-1. It gets all the elements by using this method on a Hashtable object.

get(Object)

ClassName

Dictionary

Purpose

Obtains the Object associated with the specified key in the Dictionary.

Syntax

public abstract Object get(Object key)

Parameters

key

The key, in the Dictionary, of the object to be fetched.

Description

The method returns the Object associated with the key specified. The element for the key is returned if the key is defined in the hash table. If the key is not defined, this method returns null. This is an abstract method and should be overridden in its subclass. The returned object is typecast to a class, which is expected to be returned in the given context.

Imports

import java.utils.Dictionary;

Returns

The element associated with the key. Return type is Object (note that any class is a subclass of Object).

See Also

The put method in the Dictionary class

Example

Refer to the getItem method in the inventory class in Listing 12-1. It uses this get method to get the element with the specified key.

isEmpty()

ClassName

Dictionary

Purpose

Boolean value indicating if the Dictionary contains any elements.

Syntax

public abstract boolean isEmpty()

Parameters

None.

Description

This method returns true if the Dictionary contains no elements. If the Dictionary contains even one element, this method returns false. This is an abstract method and should be overridden in its subclass.

Imports

import java.utils.Dictionary;

Returns

True if empty and false if the Dictionary contains one or more elements.

See Also

The elements method in Dictionary class

Example

Refer to the listAll()method in the inventory class in Listing 12-1. It checks if the hash table is empty using this method.

keys()

ClassName

Dictionary

Purpose

Provides an enumeration of the Dictionary's keys.

Syntax

public abstract Enumeration keys()

Parameters

None.

Description

This method returns an enumeration of the keys in Dictionary. This is an abstract method and should be overridden in its subclass. The enumeration that is returned can be used to list the keys sequentially.

Imports

import java.utils.Dictionary;

Returns

An Enumeration of the Dictionary's keys. Return type is Enumeration.

See Also

The elements method in the Dictionary class; the Enumeration interface

Example

Refer to the listAll()method in the inventory class in Listing 12-1. It lists all the elements with the keys by using this method on a Hashtable object.

put(Object, Object)

ClassName

Dictionary

Purpose

Puts the specified Object into the Dictionary using the specified key.

Syntax

public abstract Object put(Object key, Object value)

Parameters

key

The key, in the Dictionary, of the object to be included.

value

The element to be put into the Dictionary.

Description

This method puts the specified Object with the given value into the Dictionary using the specified key. After inserting the new value, the old value is removed from the table and returned. The old value corresponding to the key is returned if it existed. If not, this method returns null. This is an abstract method and should be overridden in its subclass.

Imports

import java.utils.Dictionary;

Returns

The element associated with the key. Return type is Object (note that any class is a subclass of Object).

See Also

The get method in the Dictionary class

Example

Refer to the populate method in the inventory class in Listing 12-1. It populates elements by using this method on a Hashtable object.

remove(Object)

ClassName

Dictionary

Purpose

Removes the specified key in the Dictionary.

Syntax

public abstract Object remove(Object key)

Parameters

key

The key of the object to be removed from the Dictionary.

Description

This method removes the specified key from the Dictionary. If the specified key is not present in the Dictionary, this method does nothing. This is an abstract method and should be overridden in its subclass. This method returns the value associated with the specified key to be removed. If the key was not found, this method returns null.

Imports

import java.utils.Dictionary;

Returns

The value of the key to be removed or null, if the key is not present in the Dictionary. Return type is Object.

See Also

The put and get methods in the Dictionary class

Example

Refer to the removeSoup method in the inventory class in Listing 12-1. It removes the Soup item by removing its key "can" by using this method on a Hashtable object.

size()

ClassName

Dictionary

Purpose

Obtains the number of elements contained within the Dictionary.

Syntax

public abstract int size()

Parameters

None.

Description

This method returns the number of elements in the Dictionary. This is an abstract method and should be overridden in its subclass.

Imports

import java.utils.Dictionary;

Returns

The number of elements in the Dictionary. Return type is int.

See Also

The isEmpty method in the Dictionary class.

Example

Refer to the removeSoup method in the inventory class in Listing 12-1. The size of the hash table is obtained using this method.

Hashtable

Purpose

Encapsulates the features of a hash table to store and retrieve values efficiently and maps keys to values

Syntax

public class Hashtable extends Dictionary implements Cloneable

Description

Hashtable subclasses the Dictionary class. It maps keys to values. Any object can be used as a key and/or value in a hash table. The object that is used as a key must implement the hashCode() and equals() methods to successfully store and retrieve objects from the hash table. The class defines the method clone() as it implements the Cloneable interface. When you create an instance of the hash table, you can specify the initial capacity of the hash table and its desired load factor. The load factor of the hash table is the ratio of the number of elements present in the table to the size of the table. This load factor is used to determine the size of the increment when the hash table's capacity has to be increased. Figure 12-7 illustrates the inheritance relationship of the Hashtable class.


Figure 12-7   Class diagram of Hashtable class

PackageName

java.util

Imports

import java.util.Hashtable;

Constructors

public Hashtable()

public Hashtable(int init_cap)

public Hashtable(int init_cap, float load_factor)

Parameters

init_cap

Initial capacity of the hash table.

load_factor

Load factor of the hash table contains the ratio of the number of elements, in the hash table, to the capacity of the table.

Example

The inventory class, in Listing 12-1, contains a member of type Hashtable.

clear()

ClassName

Hashtable

Purpose

Clears the hash table so that there are no elements in it.

Syntax

public synchronized void clear()

Parameters

None.

Description

The method removes all the elements in the hash table and clears it.

Imports

import java.utils.Hashtable;

Returns

None.

Example

Refer to the reset()method in the inventory class in Listing 12-1. It uses this clear method to clear the hash table.

clone()

ClassName

Hashtable

Purpose

Creates and returns a clone of the hash table.

Syntax

public synchronized Object clone()

Parameters

None.

Description

This method creates a clone of the hash table and returns a handle to it. A shallow copy of the hash table is made with its characteristics. None. of the elements or keys of the hash table are cloned in this operation. This cloning operation is relatively expensive. This method overrides the clone method of class Object. Typecast the object returned to Hashtable for further operations. This method is defined as the Hashtable class and implements the Cloneable interface.

Imports

import java.utils.Hashtable;

Returns

A handle to the clone hash table. Return type is Object.

Example

Refer to Listing 12-1. In the populate method, this clone method is used to create a backup of the original hash table and is kept for future comparisons.

contains(Object)

ClassName

Hashtable

Purpose

Checks if the specified object is an element in the Hashtable.

Syntax

public synchronized boolean contains(Object value)

Parameters

value

The value associated with the element we are searching.

Description

This method checks to see if the specified element is in the Hashtable. It returns true if the object is in the hash table, false if it is not. If the specified value is null, this method throws a NullPointerException. Note that searching for a specified object in a hash table is more expensive than searching for a key in the hash table.

Imports

import java.utils.Hashtable;

Returns

If the object is in the hash table, the method returns true. If the object is not in the hash table, the method returns false. Return type is boolean.

See Also

The containsKey method in the Hashtable class

Example

Refer to the findChanges method in the inventory class in Listing 12-1. It uses the contains method to find out the newly added items.

containsKey(Object)

ClassName

Hashtable

Purpose

Checks if an element exists in the hash table associated with the specified key.

Syntax

public synchronized boolean containsKey(Object key)

Parameters

key

The key of the element for which we are searching.

Description

This method checks to see if an object associated with the specified key is in the Hashtable. It returns true if the object is in the hash table, false if it is not. If the specified key is null, this method throws a NullPointerException. Note that searching for an object using its key in a hash table is less expensive than searching for the object itself in the hash table.

Imports

import java.utils.Hashtable;

Returns

If the object associated with the specified key is in the hash table, the method returns true. If the object is not in the hash table, the method returns false. Return type is boolean.

See Also

The contains method in the Hashtable class

Example

Refer to the findChanges method in the inventory class in Listing 12-1. It uses the containsKey method to find the sections with no item.

elements()

ClassName

Hashtable

Purpose

An enumeration of the elements is returned.

Syntax

public synchronized Enumeration elements()

Parameters

None.

Description

This method returns an enumeration of the elements in Hashtable. This overrides the elements method in the Dictionary class. The enumeration that is returned can be used to fetch the elements sequentially.

Imports

import java.utils.Hashtable;

Returns

An Enumeration of elements. Return type is Enumeration.

See Also

The keys method in the Hashtable class; the Enumeration interface

Example

Refer to the listAll() method in the inventory class in Listing 12-1. It gets all the elements by using this method on the Hashtable object.

get(Object)

ClassName

Hashtable

Purpose

Returns the Object associated with the specified key in the Hashtable.

Syntax

public synchronized Object get(Object key)

Parameters

key

The key, in the Hashtable, of the object to be fetched.

Description

This method returns the Object associated with the specified key. The element for the key is returned if the key is defined in the hash table. If the key is not defined, this method returns null. This overrides the get method in the Dictionary class.

Imports

import java.utils.Hashtable;

Returns

The element associated with the key. Return type is Object.

See Also

The put method in the Hashtable class

Example

Refer to the getItem method in the inventory class in Listing 12-1. It uses the get method for getting the element with the specified key.

isEmpty()

ClassName

Hashtable

Purpose

Boolean value indicating whether or not the Hashtable contains any elements.

Syntax

public boolean isEmpty()

Parameters

None.

Description

This method returns true if the Hashtable contains no elements. If the Hashtable contains even one element, this method returns false. This method overrides the isEmpty method in class Dictionary.

Imports

import java.utils.Hashtable;

Returns

True if empty and false if the Hashtable contains one or more elements.

See Also

The elements method in the Hashtable class

Example

Refer to the listAll()method in the inventory class in Listing 12-1. It checks if the hash table is empty using this method.

keys()

ClassName

Hashtable

Purpose

Obtains an enumeration of the Hashtable's keys.

Syntax

public synchronized Enumeration keys()

Parameters

None.

Description

This method returns an enumeration of the keys in Hashtable. This method overrides the keys method in the Dictionary class. The enumeration that is returned can be used to list the keys sequentially.

Imports

import java.utils.Hashtable;

Returns

An Enumeration of the Hashtable's keys. Return type is Enumeration.

See Also

The elements method in the Hashtable class; the Enumeration interface

Example

Refer to the listAll()method in the inventory class in Listing 12-1. It lists all the elements with the keys by using this method on a Hashtable object.

put(Object, Object)

ClassName

Hashtable

Purpose

Puts the specified Object into the Hashtable using the specified key.

Syntax

public synchronized Object put(Object key, Object value)

Parameters

key

The key, in the Hashtable, of the object to be put.

value

The element to be put into the Hashtable.

Description

This method puts the specified Object of given value into the Hashtable using the specified key. After inserting the new value, the old value is removed and returned by this method if it existed. If not, this method returns null. The key and the value cannot both be null. The element that is put into the hash table may be retrieved using the get method in the Hashtable class, by specifying the same key. This method overrides the put method in the Dictionary class.

Imports

import java.utils.Hashtable;

Returns

The element associated with the key. Return type is Object.

See Also

The get method in Hashtable class

Example

Refer to the populate method in the inventory class in Listing 12-1. It populates elements by using this method on a Hashtable object.

rehash()

ClassName

Hashtable

Purpose

The content of the hash table is rehashed into a bigger hash table.

Syntax

protected void rehash()

Parameters

None.

Description

This method rehashes the contents of the hash table into a bigger table. This method is automatically invoked when the size of the Hashtable exceeds the threshold as more elements are added to the table. This is a protected method and hence can be used only by the methods within the java.util package.

Imports

import java.utils.Hashtable;

Returns

None.

Example

This method can be used only in a class that is part of the java.util package, so it should have package java.util as the first statement in the file. Then it can be used in the class on a hash table object.

remove(Object)

ClassName

Hashtable

Purpose

Removes the specified key in the Hashtable.

Syntax

public synchronized Object remove(Object key)

Parameters

key

The key of the object to be removed from the Hashtable.

Description

This method removes the specified key from the Hashtable. If the specified key is not present in the Hashtable, there is no effect. This method overrides the remove method in the Dictionary class. This method returns the value associated with the specified key to be removed. If the key is not found, this method returns null.

Imports

import java.utils.Hashtable;

Returns

The value of the key to be removed or null if the key is not present in the Hashtable. The return type is Object.

See Also

The put and get methods in class Hashtable

Example

Refer to the removeSoup method in the inventory class in Listing 12-1. It removes the Soup item by removing its key "can" by using this method on a Hashtable object.

size()

ClassName

Hashtable

Purpose

Obtains the number of elements contained in the Hashtable.

Syntax

public int size()

Parameters

None.

Description

This method returns the number of elements in the Hashtable. This method overrides the size method in the Dictionary class.

Imports

import java.utils.Hashtable;

Returns

The number of elements in the Hashtable. Return type is int.

See Also

The isEmpty method in the Hashtable class

Example

Refer to the removeSoup method in the inventory class in Listing 12-1. The size of the hash table is obtained using this method.

toString()

ClassName

Hashtable

Purpose

Converts the instance of Hashtable to its string form.

Syntax

public synchronized String toString()

Parameters

None.

Description

This method converts the target Hashtable object to its string form. It is used mostly for debugging purposes. The converted string form of the hash table instance is returned as a lengthy String object. This method overrides the toString method in the Object class. The string contains a list of <key, object> pair represented as strings.

Imports

import java.utils.Hashtable;

Returns

The string form of the Hashtable object is returned. Return type is String.

Example

Refer to the table() method in the inventory class in Listing 12-1.

Properties

Purpose

Class containing the persistent properties of the associated object.

Syntax

public class Properties extends Hashtable

Description

Properties subclasses the class Hashtable. This contains the persistent properties of the associated object, whose properties are stored in the hash table. The contents can be saved or loaded from a stream. This class contains a protected member variable named defaults. If a property is not found in the object, it is searched for in the default properties list. This class allows arbitrary nesting of properties. This class is most widely used with the System class to obtain system properties like user name, environment, and so on. Figure 12-8 illustrates the inheritance relationship of class Properties.


Figure 12-8   Class diagram of Properties class

PackageName

java.util

Imports

import java.util.Properties;

Constructors

public Properties()

public Properties(Properties defaults)

Parameters

defaults

Initial specified default properties.

Example

The propDemo class in Listing 12-2 demonstrates the methods in the Properties class. The Properties object member in the System class in the java.lang package is used for demonstration.

Listing 12-2 propDemo.java: Demonstrating the usage of methods in the Properties class

import java.util.*;
import java.io.*;
import java.lang.*;

class propDemo

public void printProps()
}

private void getProp(String prop)

private void changeProperties(String file_name) catch(IOException ioe)

}

private void saveProperties(String file_name) catch(IOException ioe)
}

public final static void main(String args[])

}

getProperty(String), getProperty(String, String)

ClassName

Properties

Purpose

Obtain the property with the specified key.

Syntax

public String getProperty(String key)

public String getProperty(String key, String defaultValue)

Parameters

key

The specified key to be searched in the property list.

defaultValue

The string to be returned, if the specified key is not found in the list.

Description

This method searches for the specified key in the property list. If it is not found in the list, the defaults in the Properties object are searched. If a property is found, it is returned. If you specify the defaultValue during the method invocation, the defaultValue is returned if the property is not found in the list or the defaults. If defaultValue is not specified and if the property is not found either in the property list or the defaults, then the method returns a null.

Imports

import java.utils.Properties;

Returns

The string form of the property searched for. Return type is String.

Example

Refer to the getProp method in Listing 12-2. The value of the specified property key is retrieved and printed to the screen using this method.

list(PrintStream)

ClassName

Properties

Purpose

The properties are listed for debugging into the specified PrintStream.

Syntax

public void list(PrintStream out)

Parameters

out

The print stream, into which the properties are to be listed.

Description

This method lists the properties into the specified print stream. This is used for debugging.

Imports

java.utils.Properties;

Returns

None.

See Also

The save method in the Properties class

Example

Refer to the main method in Listing 12-2. The list method is used to list the properties of the System object to the screen.

load(InputStream)

ClassName

Properties

Purpose

Loads the properties from the specified InputStream.

Syntax

public void load(InputStream in)

Parameters

in

The input stream that the properties are loaded from.

Description

This method loads the properties from the specified input stream. If there is an error in reading from InputStream, an IOException is thrown.

Imports

import java.utils.Properties;

Returns

None.

See Also

The save method in the Properties class

Example

Refer to the changeProperties method in Listing 12-2. The properties defined in file myJava.prop are loaded as the new properties for System object.

propertyNames()

ClassName

Properties

Purpose

Enumerates the property keys.

Syntax

public Enumeration propertyNames()

Parameters

None.

Description

All the keys used for properties in the Properties hash table are enumerated. The enumeration that is formed is returned by this method. You can use the enumeration to access the elements sequentially.

Imports

import java.utils.Properties;

Returns

The Enumeration of the keys is returned. Return type is Enumeration.

See Also

Enumeration interface

Example

Refer to the listAll method in Listing 21-2. All the elements are printed to the screen using the method propertyNames to get the enumeration of the elements.

save(OutputStream, String)

ClassName

Properties

Purpose

Saves the properties to the specified OutputStream.

Syntax

public void save(OutputStream out, String header)

Parameters

out

The output stream that the properties are saved to.

header

Comment to be used at the top of the output stream object.

Description

This method saves the properties to the specified output stream. The specified header is included as a comment at the top of the output file if the output stream is a file stream, or the header is printed at the top as a comment.

Imports

import java.utils.Properties;

Returns

None.

See Also

The load method in the Properties class

Example

Refer to the saveProperties method in Listing 12-2. The properties of System object are saved to the specified file.

Vector

Purpose

Class representing an extensible array designed for space optimization.

Syntax

public class Vector extends Object implements Cloneable

Description

Vector is an extensible array designed for storage optimization. Each vector maintains a capacity and capacityIncrement to optimize storage management. The capacity of the Vector is always at least the size of the Vector. Because a vector increases by chunks of memory of size capacityIncrement, the capacity of the vector is usually larger than the vector size. If you specify a greater capacity value during the construction of Vector, then the amount of incremental reallocation will be reduced. This results in better storage management, but if the specified capacity is too large, then storage is wasted. You should decide the size with this in mind. Even if you ignore the capacity while constructing the Vector, it will still work fine. It will simply be less efficient in terms of storage management. This class implements the Cloneable interface. So the clone()method is defined in it. The Vector class has three variables: elementData, elementCount, and capacityIncrement. The elementData variable is the buffer where elements are stored. The elementCount variable contains the number of elements in the buffer. The capacityIncrement variable contains the size of the increment. Figure 12-9 illustrates the inheritance relationship of the Vector class.


Figure 12-9   Class diagram of Vector class

PackageName

java.util

Imports

import java.util.Vector;

Constructors

public Vector()

public Vector(int init_capacity)

public Vector(int init_capacity, int capacityIncrement)

Parameters

init_capacity

Initial specified capacity of the Vector.

capacityIncrement

The size of the increment. If it is 0 then the capacity is doubled every time the vector needs to grow.

Variables

protected Object elementData[]

protected int elementCount

protected int capacityIncrement

Example

The guestBook class, in Listing 12-3, is used to illustrate the usage of the Vector class to create an object whose size is not known in advance and whose size will vary with time. The member variable guests is an object of type Vector.

Listing 12-3 guestBook.java: A guest book maintained using the Vector class to keep log of guests

import java.util.*;

class guestBook

private void initialGuests()

private int bookCapacity()

private boolean visited(Object guest)

private Object guestNo(int number)

protected void listAll()
/* String str[] = new String[3];
guests.copyInto(str); */


protected void minSize(int min)
private void analyze()
private void replace(Object g1, Object g2)
private void change(Object g1, Object g2)

Vector backup;

protected void makeBackup()

private void newcapacity(int cap)
public final static void main(String args[])

addElement(Object)

ClassName

Vector

Purpose

Adds the specified element to the Vector.

Syntax

public final synchronized void addElement(Object element)

Parameters

element

The object to be added to the vector.

Description

This method adds the specified element to the end of the vector. The added element becomes the last element in the vector. If the size of the vector is equal to the capacity of the vector before adding the element, then the size of the vector is increased by the size of capacityIncrement.

Imports

import java.utils.Vector;

Returns

None.

See Also

The insertElementAt method in the Vector class

Example

Refer to the initialGuests method in Listing 12-3. Guests are added to the guests Vector using this addElement method.

capacity()

ClassName

Vector

Purpose

Obtains the current capacity of the vector.

Syntax

public final int capacity()

Parameters

None.

Description

This method gets the current capacity of the vector.

Imports

import java.utils.Vector;

Returns

The current capacity of the vector; the return type is int.

See Also

The ensureCapacity method in the Vector class

Example

Refer to the bookCapacity method in Listing 12-3. The capacity method is used to return the capacity of the guests vector.

clone()

ClassName

Vector

Purpose

Clones the target Vector object.

Syntax

public synchronized Object clone()

Parameters

None.

Description

This method creates a clone of the vector and returns a handle to it. A shallow copy of the vector is made with its characteristics. None of the elements of the vector are cloned in this operation. This cloning operation is a relatively expensive operation. This method overrides the clone method of the Object class. For further operations, typecast the Object returned to Vector type. This method is defined as the Vector class implements the Cloneable interface

Imports

import java.utils.Vector;

Returns

A handle to the cloned instance of the Vector. Return type is Object, which you can typecast to Vector.

See Also

The insertElementAt method in the Vector class.

Example

Refer to the makeBackup method in Listing 12-3. A new copy of the member guests is made by using the clone method on the guests object. This forms the backup member.

contains(Object)

ClassName

Vector

Purpose

Checks if the specified object is an element in the Vector.

Syntax

public final boolean contains(Object elem)

Parameters

elem

The element that we are searching for.

Description

This method checks if the specified element is in the Vector. It returns true if the object is in the vector, false if it is not. If the specified value is null, then this method throws a NullPointerException.

Imports

import java.utils.Vector;

Returns

If the object is in the vector, the method returns true. If the object is not in the vector, the method returns false. Return type is boolean.

Example

Refer to the visited method in Listing 12-3. It verifies if the specified guest has visited, by checking if the name is in the guests vector. This is implemented using the contains method on the vector guests.

copyInto(Object[])

ClassName

Vector

Purpose

Copies the elements of the vector into the specified array.

Syntax

public final synchronized void copyInto(Object newArray[])

Parameters

newArray

The array that the elements of the vector are copied into.

Description

This method copies the elements in the vector into the specified array. Note that the clone() method creates a vector and does not copy the elements. This method copies the elements into the array. If the array size is less than the size of the vector, an ArrayIndexOutOfBoundsException is thrown.

Imports

import java.utils.Vector;

Returns

None.

Example

Refer to the listAll method in Listing 12-3. If you uncomment the lines where the elements are copied into a three element array, an exception will be thrown.

elementAt(int)

ClassName

Vector

Purpose

Obtain the element in the vector at the specified index.

Syntax

public final synchronized Object elementAt(int index)

Parameters

index

The index position of the element that this method retrieves.

Description

This method gets the element at the specified index in the vector and returns the element. If the specified index is more than the size of the vector, then it throws an ArrayIndexOutOfBoundsException.

Imports

java.utils.Vector;

Returns

The element at the specified index in the target vector object. Return type is Object.

See Also

The setElementAt method in the Vector class

Example

Refer to the guestNo method in Listing 12-3. It returns the guest name which is the specified numbered person to visit. It uses the elementAt method of the Vector class to get the required name.

elements()

ClassName

Vector

Purpose

Obtains an enumeration of the elements.

Syntax

public final synchronized Enumeration elements()

Parameters

None.

Description

This method returns an enumeration of the elements in a vector. The enumeration that is returned can be used to fetch the elements sequentially from the vector.

Imports

import java.utils.Vector;

Returns

An Enumeration of elements in the vector. Return type is Enumeration.

See Also

The Enumeration interface

Example

Refer to the listAll method in Listing 12-3. The enumeration of the guests is obtained by using this elements() method.

ensureCapacity(int)

ClassName

Vector

Purpose

Verifies if the Vector has at least the specified capacity.

Syntax

public final synchronized void ensureCapacity(int minCapacity)

Parameters

minCapacity

The desired minimum capacity of the vector.

Description

The method makes sure that the target Vector object has at least the specified minimum capacity. If so, it does nothing. If the vector capacity is less than the minimum capacity, then the capacity of the vector is increased to the desired minimum.

Imports

import java.utils.Vector;

Returns

None.

See Also

The capacity method in the Vector class

Example

Refer to the minSize method in Listing 12-3, which ensures that the guest book capacity is at least the specified minimum.

firstElement()

ClassName

Vector

Purpose

Obtains the first element in the vector.

Syntax

public final synchronized Object firstElement()

Parameters

None.

Description

This method returns the first element in the sequence of the target Vector object. If the sequence is empty, this method throws a NoSuchElementException.

Imports

import java.utils.Vector;

Returns

The first element in the vector. Return type is Object.

See Also

The lastElement method in the Vector class.

Example

Refer to the analyze method in Listing 12-3. The first visitor is found by using the firstElement method on the guests vector.

indexOf(Object), indexOf(Object, int)

ClassName

Vector

Purpose

Obtains the index of the specified object in the vector.

Syntax

public final int indexOf(Object element)

public final int indexOf(Object element, int startFrom)

Parameters

element

The object to be searched for in the vector.

startFrom

The index location from which to start searching for the element in the vector.

Description

This method searches for the specified element and returns the index position of the element in the vector, if the element is in the vector. If the element is not in the vector, an ArrayIndexOutOfBoundsException is thrown. If you specify the index to start the search from, as a part of the method call, then the search starts from the specified index in the vector.

Imports

import java.utils.Vector;

Returns

The index position of the searched element in the vector.

See Also

The lastIndexOf(Object) and lastIndexOf(Object, int) methods in the class Vector

Example

Refer to the analyze method in Listing 12-3. The number of guests who arrived after David is ascertained by using the index of David's entry in the guests vector. The indexOf method is used to get the information.

insertElementAt(Object, int)

ClassName

Vector

Purpose

Inserts the specified element at the specified index.

Syntax

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

Parameters

element

The element to be inserted into the vector.

index

The index location where the specified element is to be inserted.

Description

This method inserts the specified element at the specified index in the vector. The indices of the elements existing at and after the index, before this insertion, are shifted accordingly and their indices are incremented by one. If the specified index is invalid, then this method throws an ArrayIndexOutOfBoundsException.

Imports

import java.utils.Vector;

Returns

None.

See Also

The removeElementAt method in the Vector class

Example

Refer to the replace method in Listing 12-3. After removing the specified object, the new object is placed at its position using the insertElementAt method of the Vector class.

isEmpty()

ClassName

Vector

Purpose

Checks to see if the Vector contains any elements.

Syntax

public final boolean isEmpty()

Parameters

None.

Description

This method returns true if the Vector contains no elements. If the vector contains even one element, this method returns false.

Imports

import java.utils.Vector;

Returns

True if empty and false if the Vector contains one or more elements; return type is boolean.

See Also

The elements method in the Vector class

Example

Refer to Listing 12-3. You can check if anyone visited by using this isEmpty method on the guests vector member. It will return true if no guests visited and false if at least one guest is in the guests vector.

lastElement()

ClassName

Vector

Purpose

Returns the last element in the vector.

Syntax

public final synchronized Object lastElement()

Parameters

None.

Description

This method returns the last element in the sequence of the target Vector object. If the sequence is empty, this method throws a NoSuchElementException.

Imports

import java.utils.Vector;

Returns

The last element in the vector. Return type is Object.

See Also

The firstElement method in the Vector class

Example

Refer to the analyze method in Listing 12-3. The last guest to visit is found by using the lastElement method.

lastIndexOf(Object), lastIndexOf(Object, int)

ClassName

Vector

Purpose

Obtains the index of the specified object in the vector by searching the object backwards.

Syntax

public final int lastIndexOf(Object element)

public final int lastIndexOf(Object element, int startFrom)

Parameters

element

The object that the vector is to be searched for.

startFrom

The index location from which to start searching for the element in the vector.

Description

This method searches backward from the end of the vector for the specified element and returns the index position of the element in the vector, if the element is in the vector. If the element is not in the vector, it returns -1. If you specify the index to start the search from as part of the method call, then the search starts from the specified index and moves backward in the vector.

Imports

import java.utils.Vector;

Returns

The index position of the searched element in the vector if the element is found; if the element is not found, it returns -1.

See Also

The firstIndexOf(Object) and firstIndexOf(Object, int) methods in the Vector class

Example

Refer to the analyze method in the guestBook class in Listing 12-3. The visitor number of Emy is found by using this method to scan the vector from the rear.

removeAllElements()

ClassName

Vector

Purpose

Removes all the elements in the vector.

Syntax

public final synchronized void removeAllElements()

Parameters

None.

Description

The method removes all the elements in the vector, leaving the vector empty.

Imports

import java.utils.Vector;

Returns

None.

See Also

The removeElement and removeElementAt methods in the Vector class

Example

Refer to Listing 12-3. You can clear all the names of the guests by invoking the removeAllElements method on the vector member, guests.

removeElement(Object)

ClassName

Vector

Purpose

Removes the specified element from the vector.

Syntax

public final synchronized boolean removeElement(Object element)

Parameters

element

The element to be removed from the vector.

Description

This method removes the specified element in the vector. If the element is not found in the vector, this method returns false. If the vector contains two or more occurrences of the element, only the first occurrence is removed. If the element is found in the vector, the method returns true after removing the element.

Imports

import java.utils.Vector;

Returns

If the element is found, this method returns true after removing the element. If the element is not found in the vector, this method returns false.

See Also

The removeAllElements and removeElementAt methods in the Vector class

Example

Refer to the replace method in Listing 12-3. After removing the guest g1 from its index position, any other instance of a guest with that name is removed or the method reports that no guest with the given name is present.

removeElementAt(int)

ClassName

Vector

Purpose

Removes the element at the specified index from the vector.

Syntax

public final synchronized void removeElementAt(int index)

Parameters

index

The index of the element to be removed from the vector.

Description

This method removes the element at the specified index in the vector. If the specified index is more than the capacity of the vector, the method throws ArrayIndexOutOfBoundsException. After deleting the element at the specified index, elements with an index greater than the specified index are decremented by one. This effectively moves the set of elements down the vector by one index position.

Imports

import java.utils.Vector;

Returns

None.

See Also

The removeAllElements and removeElement methods in the Vector class

Example

Refer to the replace method in Listing 12-3. The index of guest g1 is first found and then the method removeElementAt is used to remove the guest name from the determined index position.

setElementAt(Object, int)

ClassName

Vector

Purpose

Sets the element at the specified index in the vector to the specified object.

Syntax

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

Parameters

elem

The specified object that is placed at the specified index in the vector.

index

The index in the vector where the new object is to be placed.

Description

This method sets the element at the specified index to the specified object. The element previously at that index is replaced by the new specified object. If the specified index is invalid, then ArrayIndexOutOfBoundsException is thrown at runtime.

Imports

import java.utils.Vector;

Returns

None.

Example

Refer to the change method in Listing 12-3. It replaces guest g1 with guest g2. Though the functionality is the same as that of the replace method, the change method implements it in a different way by setting the element at the determined index location using the setElementAt method.

setSize(int)

ClassName

Vector

Purpose

Sets the size of the vector to the specified size.

Syntax

public final synchronized void setSize(int newSize)

Parameters

newSize

New size that the vector is set to.

Description

This method sets the size of the vector to the specified newSize. If the specified newSize is more than the size of the vector before the method is invoked, then the extra elements in the vector are set to null. Whereas, if the specified newSize is less than the size of the method before the method is invoked, then the vector is shrunk to the specified newSize and the excess elements are discarded.

Imports

import java.utils.Vector;

Returns

None.

See Also

The size method in the Vector class

Example

Refer to the newcapacity method in Listing 12-3. The specified capacity is set to be the new capacity by using the setSize method on the guests vector object.

size()

ClassName

Vector

Purpose

Obtains the size of the vector.

Syntax

public final int size()

Parameters

None.

Description

This method returns the size of the vector; that is, the number of elements in the vector and not the capacity of the vector. The capacity of the vector can be greater than the size of the vector. Whenever the size is about to exceed the capacity of the vector, the capacity is incremented by an amount contained in capacityIncrement.

Imports

import java.utils.Vector;

Returns

None.

See Also

The capacity and setSize methods in the Vector class

Example

Refer to the newcapacity method in Listing 12-3. The size before and after trimming the capacity to specified size is obtained using the size method.

toString()

ClassName

Vector

Purpose

Converts the instance of Vector to its string form.

Syntax

public final synchronized String toString()

Parameters

None.

Description

The method converts the target Vector object to its string form, used mostly for debugging purposes. The converted string form is returned as a lengthy String object. This method overrides the toString method in class Object.

Imports

import java.utils.Vector;

Returns

The string form of the Vector object is returned. Return type is String.

Example

Refer to Listing 12-3. You can invoke guests.toString() in any of the member methods in the guestBook class. It will convert the guests vector to string form containing the key-element pair of the vector.

trimToSize()

ClassName

Vector

Purpose

Reduces the capacity of the vector to the size of the vector.

Syntax

Public final synchronized void trimToSize()

Parameters

None.

Description

This method reduces the capacity of the vector to the size of the vector. At any point, there can be excess allocated space in the vector depending on the capacityIncrement value and size of the vector. Using this method, the excess allocated space can be reclaimed for storage management. After using this method, space is reallocated for any new insertions into the vector.

Imports

import java.utils.Vector;

Returns

None.

See Also

The capacity, size, and setSize methods in the Vector class.

Example

Refer to the newcapacity method in Listing 12-3. The size of the guests vector is trimmed to the capacity by using this trimToSize method. The changes resulting from the use of this method are observed from the information printed before and after the change.

Stack

Purpose

Class encapsulating the Last-In-First-Out(LIFO) stack of objects.

Syntax

public class Stack extends Vector

Description

Stack is the encapsulation of a Last-In-First-Out stack of objects. The object inserted last is at the top of the stack. It can be retrieved using the pop method. An object is put on the stack using the push method. Elements not at the top of the stack cannot be accessed until all the objects above it in the stack are popped out. Figure 12-10 illustrates the inheritance relationship of class Stack.


Figure 12-10   Class diagram of Stack class

PackageName

java.util

Imports

import java.util.Stack;

Constructors

public Stack()

Parameters

None.

Example

The class stackDemo in Listing 12-4 has a member st, of type Stack.

Listing 12-4 stackDemo.java: Demonstrating the usage of the Stack class and its methods

import java.util.*;

class stackDemo

public void populateStack()

public void check(Object obj)

private void replaceTop(Object obj)

private void clearAll()

public final static void main(String args[])

empty()

ClassName

Stack

Purpose

Boolean value indicating if there is any object on the stack.

Syntax

public boolean empty()

Parameters

None.

Description

This method returns true if the Stack contains no objects. If the stack contains even one object, this method returns false.

Imports

import java.utils.Stack;

Returns

True if the Stack is empty and false if the Stack contains one or more objects.

Example

Refer to the clearAll method in Listing 12-4. After clearing all the elements from the stack, this method verifies that the stack is empty.

peek()

ClassName

Stack

Purpose

Peeks at the element at the top of the stack.

Syntax

public Object peek()

Parameters

None.

Description

This method obtains the object at the top of the stack. This method does not affect the elements on the stack. The top object on the stack remains on the stack, but only a copy of it is returned. If the stack contains no element, this method throws EmptyStackException at runtime.

Imports

import java.utils.Stack;

Returns

A copy of the object at the top of the stack, if the stack is not empty.

See Also

The pop method in the Stack class

Example

Refer to the replaceTop method in Listing 12-4. In this method, the top element is replaced by a specified element. Before popping out the top element, the peek method is used to find the top element.

pop()

ClassName

Stack

Purpose

Obtains the element at the top of the stack.

Syntax

public Object pop()

Parameters

None.

Description

This method obtains the object at the top of the stack. This method removes the object from the top of the stack and returns it, leaving the stack with one less element. If the stack is empty, this method throws an EmptyStackException during runtime.

Imports

import java.utils.Stack;

Returns

The object at the top of the stack, if the stack is not empty.

See Also

The peek and push methods in the Stack class

Example

Refer to the replaceTop method in the stackDemo class in Listing 12-4. The top element in the stack is popped off using this method before the specified element is pushed onto the stack.

push(Object)

ClassName

Stack

Purpose

Pushes the specified object onto the stack.

Syntax

public Object push(Object obj)

Parameters

obj

The object to be pushed onto the stack.

Description

This method pushes the specified object onto the stack. The object is placed on top of the stack. If the pop method is invoked, the last inserted object will be popped off the stack. This method places the object onto the stack and returns a handle to the object

Imports

import java.utils.Stack;

Returns

The object at the top of the stack, after placing it at the top.

See Also

The pop method in the Stack class

Example

Refer to the populateStack method in Listing 12-4. Elements are added to the stack member by using the push method of class Stack.

search(Object)

ClassName

Stack

Purpose

Searches for the specified object in the stack.

Syntax

public int search(Object obj)

Parameters

obj

The object to be searched in the stack.

Description

This method searches for the specified object in the stack. If the object is found, its index position from the top of the stack is returned. If the object is not found, this method returns -1. This method is useful to search for items within the stack without affecting the stack structure.

Imports

import java.utils.Stack;

Returns

The index location of the object searched for in the stack. If it is not found, a value of -1 is returned.

Example

Refer to the check method in Listing 12-4. The presence, in the stack, of the specified object is verified by using the search method in class stack.

Enumeration

Purpose

Interface specifying methods to enumerate a set of objects.

Syntax

public interface Enumeration extends Object

Description

The Enumeration interface specifies a set of methods: hasMoreElements() and nextElement(). They are used to enumerate or count through a set of values. The enumeration is consumed as you use it to access the elements and you cannot get back the used enumeration. So the elements can be counted only once. You have to obtain the enumeration again if you want to access an enumeration earlier accessed. Figure 12-11 illustrates the inheritance relationship of interface Enumeration.


Figure 12-11   Interface diagram of Enumeration

PackageName

java.util

Imports

import java.util.Enumeration;

Example

Refer to Listing 12-4. All the guests are listed in the listAll method. This is done by first getting the enumeration of guests by using the elements() method of class Vector.

hasMoreElements()

Interface

Enumeration

Purpose

Determines if the enumeration contains more elements.

Syntax

public abstract boolean hasMoreElements()

Parameters

None.

Description

This method checks if the enumeration has more elements. It returns true if the enumeration has more elements, and returns false if the enumeration does not have more elements. This is an abstract method, as it is in an interface and it should be defined in the class implementing the interface Enumeration.

Imports

import java.utils.Enumeration;

Returns

The boolean value true is returned if the enumeration has more elements. If the enumeration is empty, the method returns false. Return type is boolean.

Example

Refer to the listAll method in Listing 12-4. All the guests are listed by getting the enumeration of elements in vector guests. This method, hasMoreElements, is used on the enumeration in the for loop construct while printing all the guest names.

nextElement()

Interface

Enumeration

Purpose

Returns the next element in the enumeration.

Syntax

public abstract Object nextElement()

Parameters

None.

Description

The method returns the next element in the enumeration. This method enumerates successive elements. If no more elements exist in the enumeration and this method is invoked, then a NoSuchElementException is thrown. This is an abstract method as it is a method in an interface and it should be defined in the class implementing the interface Enumeration.

Imports

import java.utils.Enumeration;

Returns

The successive object in the enumeration is returned. Return type is Object.

Example

Refer to the method listAll in Listing 12-4. All the guests are listed by getting the enumeration of elements in vector guests. This method, nextElement, is used on the enumeration in the for loop construct while printing all the guest names.

EmptyStackException

Purpose

A Runtime exception signaling an empty stack.

Syntax

public class EmptyStackException extends RuntimeException

Description

If a method tries to access an element in an empty stack, EmptyStackException is thrown. For example, it is thrown when you try to use pop() method on an empty stack. It is a runtime exception and hence, need not be declared to be thrown. The constructor of this exception does not have any detailed message associated with it that describes the exception. Figure 12-12 illustrates the inheritance relationship of class EmptyStackException.


Figure 12-12   Class diagram of EmptyStackException class

PackageName

java.util

Imports

import java.util.EmptyStackException;

Constructors

public EmptyStackException()

Parameters

None.

Example

If you try to replace the top of the stack using the replaceTop method before populating the stack, it will throw an EmptyStackException. Try uncommenting the code before populate method in the main method in Listing 12-4.

NoSuchElementException

Purpose

A Runtime exception signaling an empty enumeration.

Syntax

public class NoSuchElementException extends RuntimeException

Description

If a method tries to access an element in an empty enumeration, NoSuchElementException is thrown. For example, it is thrown when you try to use the firstElement() or lastElement() methods on an empty enumeration sequence. It is a runtime exception and hence, need not be declared to be thrown. The constructor of this exception does not have any detailed message associated with it that describes the exception. Figure 12-13 illustrates the inheritance relationship of class NoSuchElementException.


Figure 12-13   Class diagram of NoSuchElementException class

PackageName

java.util

Imports

import java.util.NoSuchElementException;

Constructors

public NoSuchElementException()

Parameters

None.

Example

Refer to Listing 12-3. If you call the analyze method before the vector is populated (when it is empty), the NoSuchElementException results when the firstElement is accessed. If you uncomment the second line in the main method in that listing, this exception is thrown.

Random

Purpose

A pseudo-random number generator class.

Syntax

public class Random extends Object

Description

The Random class is used to generate a stream of pseudo-random numbers. One of the constructors is used to create a new random number generator. You can specify a seed of type long or a random number generator with no seed. When you specify a seed, the same stream of pseudo-random numbers can be repeated using the same seed to start the generator. If you don't specify a seed, a value based on the current time is used as a seed. If you want to reset the seed to a different value, you can use the setSeed method. To obtain successive pseudo-random numbers, you can use one of the other methods in this class (except the setSeed method). Figure 12-14 illustrates the inheritance relationship of class Random.


Figure 12-14   Class diagram of Random class

PackageName

java.util

Imports

import java.util.Random;

Constructors

public Random()

public Random(long seed)

Parameters

seed

The single long seed used to create a random number generator.

Example

The randomDemo class in Listing 12-5 illustrates the generation of random numbers.

Listing 12-5 randomDemo.java: Usage of random numbers

import java.util.Random;

class randomDemo

private void doubleGen()
private void floatGen()
System.out.println('nn');

private void gaussianGen()

private void intGen()
System.out.println('nn');

private void longGen()
System.out.println('nn');


public final static void main(String args[])

nextDouble()

ClassName

Random

Purpose

Generates a pseudo-random uniformly distributed double value between 0.0 and 1.0.

Syntax

public double nextDouble()

Parameters

None.

Description

This method generates a pseudo-random number, uniformly distributed double value between 0.0 and 1.0.

Imports

import java.utils.Random;

Returns

A double value between 0.0 and 1.0.

Example

Refer to the doubleGen method in Listing 12-5. Random double values are generated with seed 10. For any number of runs of the program, the same sequence of double values is generated.

nextFloat()

ClassName

Random

Purpose

Generates a pseudo-random uniformly distributed float value between 0.0 and 1.0.

Syntax

public float nextFloat()

Parameters

None.

Description

This method generates a pseudo-random number, uniformly distributed float value between 0.0 and 1.0.

Imports

import java.utils.Random;

Returns

A float value between 0.0 and 1.0.

Example

Refer to the floatGen method in Listing 12-5. The float values above 0.5 are printed to the screen. Each time this program is run, the sequence differs. This is because the Random object is not created with a fixed seed, as in the case of doubleGen.

nextGaussian()

ClassName

Random

Purpose

Generates a pseudo-random, Gaussian, distributed double value between 0.0 and 1.0.

Syntax

public double nextGaussian()

Parameters

None.

Description

This method generates a pseudo-random number, Gaussian, distributed double value with mean 0.0 and standard deviation 1.0.

Imports

import java.utils.Random;

Returns

A double value.

Example

Refer to the gaussianGen method in Listing 12-5. It generates values of type double. As you will note, it can generate negative values, whereas, the doubleGen method generates only positive double. This illustrates the difference between nextDouble and nextGaussian, which differs not only in distribution but also in possible values generated.

nextInt()

ClassName

Random

Purpose

Generates a pseudo-random uniformly distributed int value.

Syntax

public int nextInt()

Parameters

None.

Description

This method generates a pseudo-random number, uniformly distributed int value.

Imports

import java.utils.Random;

Returns

An int value.

Example

Refer to the inGen method in Listing 12-5. Positive integer values are printed to the output stream. In this method, the generated sequence of numbers varies for every run of the program.

nextLong()

ClassName

Random

Purpose

Generates a pseudo-random uniformly distributed long value.

Syntax

public long nextLong()

Parameters

None.

Description

This method generates a pseudo-random number uniformly distributed long value.

Imports

import java.utils.Random;

Returns

A long value.

Example

Refer to the longGen method in Listing 12-5. The sequence of numbers generated remains the same because the seed is set to 300 using the setSeed function. Those numbers generated below 1 million are printed to the output stream.

setSeed(long)

ClassName

Random

Purpose

Sets the seed of the random number generator using the specified single long seed.

Syntax

public synchronized void setSeed(long seed)

Parameters

seed

The seed for the pseudo-random number generator.

Description

This method sets the seed for the pseudo-random number generator to the specified seed. This method can also be used to reset earlier seed values. A random number generator with a specified seed generates a repeatable stream of pseudo-random numbers.

Imports

import java.utils.Random;

Returns

None.

Example

Refer to the longGen method in Listing 12-5. The sequence of numbers generated remains the same bacause the seed is set to 300 using the setSeed function. Generated numbers below 1 million are printed to the output stream.

Java Appointment Organizer Applet

The applet for this chapter is an appointment organizer. Using Java's AWT components you will provide the user-interface for entering appointment details. The user will enter a date, time, and a text string describing the appointment. Users can save the appointment information and then retrieve it by specifying the data and the time. To develop the user-interface for the organizer, you'll create the following components:

1.  A text field for entering the date

2.  A text field for entering the hour of appointment

3.  A text field for entering the minutes past the hour at which the appointment is scheduled

4.  A choice button to select between setting an appointment and finding the appointment at a given date and time

5.  A text area to enter appointment details

6.  A text area to display the details of the requested appointment

7.  A button to confirm the user's selection of setting or finding an appointment. Appropriate action will be taken after this confirmation button is clicked.

The Java Appointment Organizer is constructed using the classes covered in this chapter. You will create a javaOrganizer class with member dates. The javaOrganizer class will subclass the Applet class, because we are building an applet. The member dates will be a dateVector object with a capacity of 31 elements. The class dateVector is a subclass of Vector. Date will be used as an index into the dateVector to map to an appointment on a given date. In this implementation, we'll consider only the present month. You can build on this design to implement for 12 months a year and for any specified year. Each object in the vector, named dates, is a hash table because the time and number of appointments will vary from day to day. On some days a person might have many appointments and on others very few. Appointments are arranged with time as the key element and description as the object. For a given index in the dateVector, an appointmentTable object is stored. The appointmentTable class is a hash table class.

The user can trigger two actions: setting up a new appointment and retrieving an appointment at a given date and time. The javaOrganizer includes methods to accomplish these two actions. Methods in the Vector, HashTable and Date classes provide the necessary functionality expected from the javaOrganizer.

Building the Project

1.  Using the bottom-up approach, we shall first design the appointmentTable class. It is a subclass of the Hashtable class. We will specify the capacity of the hash table to be 10. In case you want to include more time, this capacity is expandable. Enter the following code to define the appointmentTable class.

class appointmentTable extends Hashtable

2.  The appointmentTable object is a part of the dates vector. We need to add functionality for this class to add appointment details for a given time. Date is determined by the index occupied by this appointmentTable object in the dates vector. We will add a method addOneAppt. This method will take two parameters: time and details. The time is the key for this table. This method will add the given appointment details with the specified key to the table. If there is already another appointment at the specified time, this method will notify the user and return without affecting the earlier appointment. Another needed functionality is the ability to retrieve an appointment detail text, given the time. The apptAt method will return the String containing the details when the time is passed as a parameter. Add the following code to the appointTable class, defined in Step 1.

public boolean addOneAppt(String time, String what)


put(time, what);
return true;


public String apptAt(String time)
return (String)this.get(time);

3.  Having defined the appointmentTable class, we will now define the dateVector class, which will subclass the Vector class. This class should have the functionality to add and retrieve appointment details. It is a Vector object with a size of 31, so we can index into 31 locations into the vector. Without much optimization, the following code defines the class and its constructor. We populate all its indices with default appointmentTable objects, so that there is a table for each day of the month.

class dateVector extends Vector

4.  Now we'll add methods to the dateVector class to add and retrieve appointment tables. Each appointmentTable object is indexed by date. To add a specified appointmentTable on a particular day, we will define a fixAppt method. It will take a date as the index into the vector and the appointmentTable as the element. The knowAppt method will find the appointment table for the specified date. It returns an object of type appointmentTable. These methods are defined here. Enter the following code into the dateVector class defined in the previous step.

public void fixAppt(appointmentTable appt, int date)
this.setElementAt(appt, date-1);


public appointmentTable knowAppt(int date)
return (appointmentTable)elementAt(date-1);

5.  Now that you have defined two classes, dateVector and appointmentTable, you need to define the javaOrganizer class. The javaOrganizer class is a public class that subclasses the Applet class because we are implementing this project as an applet. The class should contain the dateVector object, dates, as its member. It will be initialized in the init() method and will contain the user interface components as its members. Enter the following code into the file javaOrganizer.java, together with classes dateVector and appointment table.

import java.util.*;
import java.awt.*;

public class javaOrganizer extends java.applet.Applet

TextArea apptEntry;
TextArea apptView;
TextField date;
TextField hrs;
TextField mins;
Choice todo;

6.  The start method in an applet is run at the start of an applet after initialization. So we will plug in an implementation of UI, into the start method, for this organizer. You can find details about the UI code in the chapters in this book which describes the Java AWT. Enter the following method into the class javaOrganizer.

public void start()

7.  Having provided the method to start the applet, the next step is to provide the necessary event handling. When a user clicks on the OK button, appropriate action is taken, depending on whether the option selected is to set the appointment or to find an appointment. The values for date, time, and details of an appointment are gathered from the user-interface. If the appointment is to be scheduled, then the setAppt method is called. This method adds an appointment to the appointmentTable object at the specified time and date. For this purpose, the appointmentTable for a specified date is retrieved and the new appointment is added. Enter the following code into the javaOrganizer class.

public boolean action(Event evt, Object arg)
if (todo.getSelectedItem().equals('FindAppt'))

return true;


public void setAppt(int date, String time, String what)

8.  The next step is to define the method for finding the appointments for a specified date and time. This method returns a String object, which is then displayed in the view area in the UI. The dateVector object is indexed by the specified date. By using the knowAppt method of the dateVector class, the appointment table for the specified date is obtained. Having obtained a handle to the dateVector for the specified date, the appointmentTable object for the specified time on that date is obtained by using the apptAt method of the appointmentTable class. Enter the following code inside the javaOrganizer class.

public String findAppt(int date, String time)

9.  Having successfully completed the implementation of the javaOrganizer class, you can compile the class, using the javac compiler. Here is the HTML file to launch this applet. Enter it in a file named org.html.

<title>Java Appointment Organizer</title>
<hr>
<applet code=javaOrganizer.class width=250 height=250>
</applet>
<hr>

You can improve on this applet by adding methods to save appointments to a file and later retrieve the appointments from the file. Figure 12-15 shows the user-interface for this javaOrganizer applet.


Figure 12-15   javaOrganizer: The Java Appointment Organizer in action

How It Works

The applet is launched by either an applet viewer or from a browser. When the applet starts, it shows a user-interface as shown in Figure 12-15. There are three text fields at the bottom of the applet. The first field is for specifying the date, the second is for entering the hour, and the third field is for entering the minutes. Once the date and time are specified, you can either set an appointment for that time or find any existing appointment at that time. The choice button to the left of the OK button can be used to select your option. In the user-interface there are two text areas: one on the left and one on the right. The text area on the left is the area where you will enter the details of an appointment. If you want to set an appointment, choose the SetAppt option in the choice button and enter the details in the text area. Once you have completed the details, press the OK button to confirm the entry. If you want to find the appointment at the specified date and time, choose the FindAppt option in the choice button and press the OK button. The details of the appointment at the specified time are displayed in the text area on the right side. You can keep track of your appointments by using this applet as long as you don't close the applet. You can provide the functionality to store the details to a file and retrieve it as needed, so that the applet can be closed at any time. You also need not worry about system crashes and power shutdowns if you extend this applet to provide that functionality. Good luck!



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 1113
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved