How Hashtable internally maintain key value pairs

How Hashtable internally maintain key value pairs

Answer:
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable

HashTable class maps keys to values and non-null object could be used as key or as value. To successfully store retrieve and store objects from HashTable the class must implements equals and hashCode method.

Hashtable instance can be initialized with two parameter initial capacity and load factor which could affect performance. Capacity is number of buckets in hash table and initial capacity is capacity at time when hash table is created.t

Default load factor is (.75) which offers very good trade-off between time and space costs. Higher values decrease space overhead but increase time cost to look up an entry these are reflected in most Hashtable operations which includes get and put.

HashTable works on hashing principle to better understand how it maintain the key value pair internally please refer this documentation  

Please have java example of HashTable below:

package com.javahonk.hashtable;

import java.util.Hashtable;
import java.util.Map.Entry;
import java.util.Set;

public class HashMapTest {

    public static void main(String[] args) {

    Hashtable<String, String> hashtable = 
        new Hashtable<String, String>();

    hashtable.put("Java", "Java");
    hashtable.put("Honk", "Honk");
    hashtable.put("Test", "Test");
    

    Set<Entry<String, String>> set = hashtable.entrySet();
    for (Entry<String, String> entry : set) {

        System.out.println("Key: " + entry.getKey() 
            + " Value: " + entry.getValue());
    }

    }

}

Output:
How Hashtable internally maintain key value pairs

Leave a Reply

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