What is Hashtable in Java with Example?

What is Hashtable in Java with Example?What is Hashtable in Java with Example?

What is Hashtable in Java with Example?
  • The underlying data-structure for Hashtable is Hashtable.
  • Insertion order is not preserved and it is based on Hashcode of keys.
  • Duplicate keys are not allowed and values can be duplicated.
  • Heterogeneous objects are allowed for both keys and values.
  • Null is not allowed for both key and value. Otherwise, we will get RuntimeException saying NullPointerException.
  • It implements Serializable and Cloneable interfaces but not RandomAccess.
  • Every method present in Hashtable is synchronized and hence Hashtable object is thread-safe.
  • Hashtable is the best choice if our frequent operation is search operation.
  • To successfully store and retrieve objects from a hash table, the objects used as keys must implement the hashCode method and the equals method.
    • It is similar to HashMap but is synchronized.
    • Hashtable stores key/value pair in the hashtable.
    • In Hashtable, we specify an object that is used as a key, and the value we want to associate to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

Constructor

1 Hashtable h=new Hashtable() Creates an empty Hashtable object with default initial capacity 11 and default fill ratio 0.75.
2 Hashtable h=new Hashtable(int initial capacity) Creates an empty Hashtable object with given capacity 11 and default fill ratio 0.75
3 Hashtable h=new Hashtable(int initial capacity, float fillratio) Creates an empty Hashtable object with given initial capacity 11 and given fill ratio 0.75
4 Hashtable h=new Hashtable(Map m) create a Hashtable with equivalent given Map object.

 

package com.java4us;

import java.util.Hashtable;

class Test {
    int i;

    Test(int i) {
        this.i = i;
    }

    public int hashCode() {
        return i;
    }

    public String toString() {
        return i + "";
    }

    public static void main(String args[]) {
        Hashtable t = new Hashtable();
        t.put(new Test(2), "Welcome");
        t.put(new Test(4), "To");
        t.put(new Test(7), "Java4us");
        t.put(new Test(9), "Dot");
        t.put(new Test(15), "Com");
        System.out.println(t); // {9=Dot, 7=Java4us, 15=Com, 4=To, 2=Welcome}
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*