What is Hashtable in Java?
Hashtable was part of the original java.util and is a concrete implementation of a
        Dictionary.
        However, with the advent of collections, Hashtable was reengineered to also
        implement the Map
            interface. Thus, Hashtable is integrated into the Collections
        Framework. It is similar to HashMap, but is synchronized.
Like HashMap, Hashtable
        stores key/value pairs in a hash table. However, neither keys
        nor values can be null.
To successfully store and retrieve objects from a hashtable, the
        objects used as keys must implement the hashCode
        method and the equals method.
Here is the topic that will cover in this post.
Java Hashtable class Diagram
 
    Java Hashtable class Declaration
Java Hashtable extends Dictionary
        abstract class and implements Map interface.
        It is synchronized class and store key/value pairs. If thread-safe implementation is not needed, it is
        recommended to use
        HashMap in place of
        Hashtable. If a thread-safe
        highly-concurrent implementation is desired, then it is recommended
        to use java.util.concurrent.ConcurrentHashMap in place of Hashtable.
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, java.io.Serializable
Here, K specifies the type of keys, and V specifies the type of values.
Java Hashtable features
- Java Hashtable inherits Dictionary abstract class.
- Java Hashtable does not permit nullkey andnullvalue.
- Java Hashtable is not an ordered collection. It does not guarantee that the order will remain constant over time.
- The iterators returned by all of this class's "collection view methods" are fail-fast. if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.
- Hashtablehas two parameters that affect its performance: initial capacity and load factor.
- Java Hashtable is synchronized legacy class.
- Java Hashtable available from JDK 1.0.
Java Hashtable constructors
Hashtable has four constructors.
| Constructor | Description | 
|---|---|
| public Hashtable() | Constructs a new empty hashtable with a default initial capacity (11) and load factor (0.75). | 
| public Hashtable(int initialCapacity) | Constructs a new empty hashtable with the specified initial capacity and default load factor (0.75). | 
| public Hashtable(int initialCapacity, float loadFactor) | Constructs a new empty hashtable with the specified initial capacity and the specified load factor. | 
| public Hashtable(Map<? extends K, ? extends V> t) | Constructs a new hashtable with the same mappings as the given Map. The hashtable is created with an initial capacity sufficient to hold the mappings in the given Map and a default load factor (0.75). | 
Java Hashtable methods
Hashtable includes all the methods defined by Dictionary abstract
        class, and all methods of implemented Map
        interface. Hashtable adds several of its own, shown in below table:
| Method | Description | 
|---|---|
| public synchronized boolean contains(Object value) | Returns true if some value equal to value exists within the hash table. Returns false if the value isn’t found. | 
| public synchronized Object clone() | Creates a shallow copy of this hashtable. All the structure of the hashtable itself is copied, but the keys and values are not cloned. This is a relatively expensive operation. | 
| public synchronized String toString() | Returns a string representation of this Hashtableobject
                in the form of a set of entries, enclosed in braces and separated
                by the ASCII characters ", " (comma and space). Each
                entry is rendered as the key, an equals sign =, and the
                associated element, where the toString method is used to
                convert the key and element to strings. | 
Example
Here is a simple program of Hashtable.
package com.walking.techie;
import java.util.Hashtable;
public class HashTableDemo {
  public static void main(String[] args) {
    Hashtable<Integer, String> hashtable = new Hashtable<>();
    hashtable.put(1, "One");
    hashtable.put(2, "Two");
    hashtable.put(3, "Three");
    hashtable.put(4, "Four");
    hashtable.put(5, "Five");
    // check hash table contains value
    System.out.println("Does hash table contain Four? : " + hashtable.contains("Four"));
    // print all key/value pairs of hash table
    System.out.println("All key-value pairs of hash table : " + hashtable);
    // print all key/value pairs of hash table using toString
    System.out.println(
        "All key-value pairs of hash table using toString method call : " + hashtable.toString());
    // size of hash table
    System.out.println("Size of hash table : " + hashtable.size());
    // remove 3 from hash table
    System.out.println("Remove 3 from hash table : " + hashtable.remove(3));
    // clone hash table
    Hashtable<Integer, String> clonedTable = (Hashtable<Integer, String>) hashtable.clone();
    // print all the key-value pairs of cloned hash table using for each
    System.out.println("\nAll key-value pairs of cloned hash table : ");
    for (Integer key : clonedTable.keySet()) {
      System.out.println("Key : " + key + " Value : " + clonedTable.get(key));
    }
    // call clear method on hash table
    hashtable.clear();
    System.out.println("\nNow size of hash table : " + hashtable.size());
  }
}
    Output of above program is shown below:
Does hash table contain Four? : true
All key-value pairs of hash table : {5=Five, 4=Four, 3=Three, 2=Two, 1=One}
All key-value pairs of hash table using toString method call : {5=Five, 4=Four, 3=Three, 2=Two, 1=One}
Size of hash table : 5
Remove 3 from hash table : Three
All key-value pairs of cloned hash table :
Key : 5 Value : Five
Key : 4 Value : Four
Key : 2 Value : Two
Key : 1 Value : One
Now size of hash table : 0
    Iterate or Traverse over Hashtable
1. Iterating Hashtable in java using iterator and KeySet
package com.walking.techie;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
public class HashtableTraversal {
  public static void main(String[] args) {
    Hashtable<Integer, String> hashtable = new Hashtable<>();
    hashtable.put(1, "One");
    hashtable.put(2, "Two");
    hashtable.put(3, "Three");
    hashtable.put(4, "Four");
    hashtable.put(5, "Five");
    // Returns a Set view of the keys contained in this hash table.
    Set<Integer> set = hashtable.keySet();
    // Returns an iterator over the elements in this set.
    Iterator<Integer> itr = set.iterator();
    while (itr.hasNext()) {
      Integer key = itr.next();
      System.out.println("Key=" + key + " Value=" + hashtable.get(key));
    }
  }
}
    Output of above program is shown below:
Key=5 Value=Five Key=4 Value=Four Key=3 Value=Three Key=2 Value=Two Key=1 Value=One
2. Iterating Hashtable in java using EntrySet and Java Iterator
package com.walking.techie;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HashtableTraversal {
  public static void main(String[] args) {
    Hashtable<Integer, String> hashtable = new Hashtable<>();
    hashtable.put(1, "One");
    hashtable.put(2, "Two");
    hashtable.put(3, "Three");
    hashtable.put(4, "Four");
    hashtable.put(5, "Five");
    // Returns a Set view of the mappings contained in this map.
    Set<java.util.Map.Entry<Integer, String>> entry = hashtable.entrySet();
    // Returns an iterator over the elements in this set.
    Iterator<Entry<Integer, String>> iterator = entry.iterator();
    while (iterator.hasNext()) {
      Map.Entry<Integer, String> entry2 = (Entry<Integer, String>) iterator.next();
      System.out.println("Key=" + entry2.getKey() + " Value=" + entry2.getValue());
    }
  }
}
    Output of above program is shown below:
Key=5 Value=Five Key=4 Value=Four Key=3 Value=Three Key=2 Value=Two Key=1 Value=One
Iterating Hashtable in java using EntrySet and Java for loop
package com.walking.techie;
import java.util.Hashtable;
import java.util.Map.Entry;
import java.util.Set;
public class HashtableTraversal {
  public static void main(String[] args) {
    Hashtable<Integer, String> hashtable = new Hashtable<>();
    hashtable.put(1, "One");
    hashtable.put(2, "Two");
    hashtable.put(3, "Three");
    hashtable.put(4, "Four");
    hashtable.put(5, "Five");
    Set<Entry<Integer, String>> entrySet = hashtable.entrySet();
    for (Entry<Integer, String> entry : entrySet) {
      System.out.println("Key=" + entry.getKey() + " Value=" + entry.getValue());
    }
  }
}
    Output of above program is shown below:
Key=5 Value=Five Key=4 Value=Four Key=3 Value=Three Key=2 Value=Two Key=1 Value=One
4. Iterating Hashtable in java using KeySet and Java for loop
package com.walking.techie;
import java.util.Hashtable;
public class HashtableTraversal {
  public static void main(String[] args) {
    Hashtable<Integer, String> hashtable = new Hashtable<>();
    hashtable.put(1, "One");
    hashtable.put(2, "Two");
    hashtable.put(3, "Three");
    hashtable.put(4, "Four");
    hashtable.put(5, "Five");
    for (Integer key : hashtable.keySet()) {
      System.out.println("Key=" + key + " Value=" + hashtable.get(key));
    }
  }
}
    Output of above program is shown below:
Key=5 Value=Five Key=4 Value=Four Key=3 Value=Three Key=2 Value=Two Key=1 Value=One
5. Iterating Hashtable in java using Java 8 forEach and lambda expression
package com.walking.techie;
import java.util.Hashtable;
public class HashtableTraversal {
  public static void main(String[] args) {
    Hashtable<Integer, String> hashtable = new Hashtable<>();
    hashtable.put(1, "One");
    hashtable.put(2, "Two");
    hashtable.put(3, "Three");
    hashtable.put(4, "Four");
    hashtable.put(5, "Five");
    // using java 8 for each and lambda expression
    hashtable.forEach((k, v) -> {
      System.out.println("Key=" + k + " Value=" + v);
    });
  }
}
    Output of above program is shown below:
Key=1 Value=One Key=2 Value=Two Key=3 Value=Three Key=4 Value=Four Key=5 Value=Five
 
 
 
 
ReplyDeleteGiven so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more .
java training in chennai | Best java training in chennai | java training | java training in chennai with placement