golden nugget online

Legacy Classes And Legacy Interface Of Collections API

Introduction 

Java versions earlier to Java2 did not contain any collections framework. They only contained some classes and an interface, which were used to store objects. These are called as Legacy classes and Legacy Interface. The Legacy classes are synchronized as opposed to the classes in the collection framework. The Legacy classes are Dictionary, Hashtable, Properties, Stack, and Vector. The Legacy interface is the Enumeration interface.

Dictionary

The Dictionary is an abstract class. It maps keys to values and operates similar to a Map. Every key and value is an object in this class. Each key is mapped to utmost one value. This mapping enables us to retrieve the value if the key is known. The Dictionary class is declared obsolete in Java2 as it is superseded by the Map class. It contains only the constructor Dictionary() 

Methods of Dictionary class

  • Enumeration elements(): Returns an enumeration containing the elements in the current dictionary.
  • Object get(Object a): Returns the value to which the object a is mapped. If the object a is not present in the dictionary, then a null object is returned.
  • Boolean IsEmpty():  Checks if the current dictionary contains any key. If it contains atleast one key, then it returns false, else it returns true.
  • Enumeration keys(): Returns an enumeration containing the keys in the current dictionary.
  • Object put(Object key, Object val): Maps the object key to the object val in the current dictionary.
  • Object remove(Object a): Removes the key specified by the object a and its value from the current dictionary and returns the value associated with a.
  • int Size():  Returns the number of entries in the current dictionary.

Hashtable

Hashtable stores key value pairs in a hash table. We must specify the key and the value to be mapped to that key. The key is hashed and the hash code is used as the index of the position at which the value is stored. The object of the Hashtable class must override the hashCode() and equals() method of the Object class. The hashCode() method is used to convert the key to its equivalent hash code, and the equals() method is used to compare two objects. The hash table contains 4 constructors.

  • Hashtable():  Create an empty hashtable with default capacity and load factor.
  • Hashtable(int cap):  Create an empty hash table with the initial capacity specified by cap and default load factor.
  • Hashtable(int cap, float load): Creates an empty hash table with the initial capacity specified by cap and the load factor specified by load.
  • Hashtable(Map m): Creates a hash table whose mappings are those of the map m

The default load factor is 0.75  and it can vary from 0.0 to 1.0. In addition to the methods of the Map interface class defines the methods.

In addition to the methods of the Map interface, the Hastable class defines some methods :

  • void clear(): Removes all the keys from the hash table.
  • Object clone(): creates a duplicate of the current hash table.
  • boolean containsKey(Object a): Checks if the hash table contains a key specified by a . If it is found then it returns true else it returns false.
  • boolean contains(Object a):  Checks if the hash table contains any key mapped to the value specified by a. If it is found then it returns true else it returns false.
  • boolean containsValue(Object a): Check if the hash table contains one or more keys mapped to value specified by a and returns true or false accordingly. This method is similar to the contains method.
  • Enumeration elements(): Returns an enumeration containing the values of the current hash table.
  • Object get(Object a): Returns the value associated with the key specified by a . If there is no such key then null is returned.
  • boolean isEmpty(): Check if the hash table is empty. It returns true if the hash table is empty and returns false if it contains at least one key.

The following example illustrates the usage of Hashtable. It uses the example of marks scored by the student.

import java.util.*;
class HashtableEg {
    public static void main(String args[]) {
        Hashtable h = golden nugget online Hastable();
        h.put("Ashish", golden nugget online Integer(70));
        h.put("Sonali", golden nugget online Integer(65));
        h.put("Soniya", golden nugget online Integer(58));
        h.put("Akash", golden nugget online Integer(80));
        h.put("Anuj", golden nugget online Integer(78));
        Enumeration e = h.elements();
        while (e.hasMoreElements()) {
            System.out.println(e.nextElement());
        }
    }
}
  • Save the file as HashtableEg.java
  • Compile the file using javac HashtableEg.java
  • Run the file using java HashtableEg

Properties

The Properties class extends the Hashtable class. The properties class represents a persistent set of properties. Each key and its value in the property list is a string. It can also contain another property list as its “defaults”. The default property list will be searched if the key is not present in the current property list. Properties class is used by many other Java classes.

  • Properties(): Creates an empty property list with no default values.
  • Properties(Properties def): Create an empty property list with the default values specified by def.

The properties class contains its own methods in addition to the methods it inherits from Hashtable.

  • String getProperty(String key):  Returns the value associated with the key specified by key in the current property list.
  • String getProperty(String key, String prop): Returns the value associated with the key in the current property list. If key is neither in the list nor in the default property list, then prop is returned.
  • void list(PrintStream out): Sends the property list to the output stream by out.
  • void list(PrintWriter str): Sends the property list to the output stream specified by str.
  • void load(InputStream in): Input a property list from the input stream specified by in
  • Enumeration propertyNames(): Returns an enumeration of the keys in the current property list.
  • Object setProperty(String key, String val): Calls the hashtable method put to associate the value specified by val with the key specified by val.
  • void store(OutputStream out, String desc): Writes the property list in the properties table to the output stream specified by out.

Vector

The Vector class implements a growable array of objects. Its components can be accessed using an integer index. Each vector maintains a capacity and capacity increment. The capacity is always greater than or equal to the vector size.

The following constructor of vector class as,

  • Vector(): creates an empty vector. Its size is 10 and capacity increment is 0.
  • Vector(Collection c):  Creates a vector containing the elements of the collection c. The elements are accessed in the order returned by the collection’s iterator.
  • Vector(int cap): Creates an empty vector with initial capacity specified by cap and capacity increment 0.
  • Vector(int cap, int inc):  Create an empty vector with initial capacity specified by cap and capacity increment specified by inc.

Below program illustrate the usage of Vector class.

import java.util.*;
class VectorEg {
    public static void main(String args[]) {
        Vector v = golden nugget online Vector();
        v.add("First");
        int i = 1;
        v.add(golden nugget online Integer(i));
        double d = 1.1;
        v.add(golden nugget online Double(d));
        v.add("Second");
        i = 2;
        v.add(golden nugget online Integer(i));
        d = 2.2;
        v.add(golden nugget online Double(d));
        Enumeration e = v.elements();
        System.out.println("The elements of the vector are as follows:\n");
        while (e.hasMoreElements()) {
            System.out.println(e.nextElement());
        }
        System.out.println("\n");
        System.out.println("The Capacity of the vector is:" + v.capacity());
        System.out.println("The Size of the vector is:" + v.size());
        System.out.println("The Second element  of the vector is:" + v.elementAt(1));
        System.out.println("The First element  of the vector is:" + v.firstElement());
        System.out.println("The Last element  of the vector is:" + v.lastElement());
        v.removeElementAt(2);
        e = v.elements();
        System.out.println("\n The Vector after removing one of its elements is as follows:\n");
        while (e.hasMoreElements()) {
            System.out.println(e.nextElement());
        }
        System.out.println("\n");
    }
}
  • Save the file as VectorEg.java
  • Compile the file using javac VectorEg.java
  • Run the file using java VectorEg

Stack

The stack class represents a last-in-first-out stack of objects and extends the Vector class. It contains a single constructor, namely Stack() that creates an empty stack. It contains five methods that allow a Vector to be treated as a stack.

  • boolean empty(): checks if the current stack is empty.
  • Object peek():  Returns the object at the top of the stack.
  • Object pop():  Removes the object at the top of the stack.
  • Object push(Object a):  Push the object a to the top of the stack
  • int search(Object a): Returns the position of the object in the stack. The position starts with 1.

Enumeration Interface

The Enumeration interface is the only legacy interface. It defines methods, which help us to enumerate the elements in a collection of objects. This interface has been suspended by Iterator. It contains only 2 methods as shown here:

  • boolean hasMoreElements(): Checks if the enumeration contains more elements. If it contains more elements, then it returns true, else it returns false.
  • Object nextElement(): Returns the next element of the enumeration. If there are no more elements to retrieve then it throws NoSuchElementException.

Summary

The collection interface is at the top of the hierarchy. It enables us to work with groups of objects. The List interface extends the Collection interface and handles sequences. The legacy classes are Dictionary, Hashtable, Properties, Stack, and vector. The legacy interface is the Enumeration interface.