Professional Documents
Culture Documents
Java API
Constructor Methods
Hashtable()
Constructs a new, empty hashtable with a default initial capacity (11) and load factor, which is 0.75.
Hashtable(int initialCapacity)
Constructs a new, empty hashtable with the specified initial capacity and default load factor, which is 0.75.
Hashtable(Map t)
Constructs a new hashtable with the same mappings as the given Map.
public interface Map An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
A simple example
This example creates 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));
Methods
void clear()
Clears this hashtable so that it contains no keys.
boolean isEmpty()
Tests if this hashtable maps no keys to values.
Enumeration elements()
Returns an enumeration of the values in this hashtable.
Enumeration keys()
Returns an enumeration of the keys in this hashtable.
5
Methods
Object get(Object key)
Returns the value to which the specified key is mapped in this hashtable.
Object put(Object key, Object value) Maps the specified key to the specified value in this hashtable. Objec remove(Object key)
Removes the key (and its corresponding value) from this hashtable
Set keySet()
Returns a Set view of the keys contained in this Hashtable
public class SortHashtable { public static void main(String[] args) { // Create and populate hashtable Hashtable ht = new Hashtable(); ht.put("ABC", "abc"); ht.put("XYZ", "xyz"); ht.put("MNO", "mno"); // Sort hashtable. Vector v = new Vector(ht.keySet()); Collections.sort(v);
MNO
mno
// Display (sorted) hashtable. for (Enumeration e = v.elements(); e.hasMoreElements();) { String key = (String)e.nextElement(); String val = (String)ht.get(key); System.out.println("Key: " + key + " Val: " + val); } } }
Output:
Key: ABC Val: abc Key: MNO Val: mno Key: XYZ Val: xyz
7
Demo
Exercise
Understand and run the java program in page7.
SortHashTable.java
HashTableApplet.java
10