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()); } } }
hi could you please see the output of the below program and explain why it is ?
public class HashTableExample {
public static void main(String []args){
Hashtable ht = new Hashtable();
ht.put(“Dev”, “Viswam”);
ht.put(“QC”,”Viswam”);
ht.put(“QC”,”Sunitha”);
ht.put(“QC”,”Darling”);
ht.put(“Dev”, “Deepak”);
ht.put(“Dev”, “Viswam”);
Iterator keys = ht.keySet().iterator();
while(keys.hasNext()){
System.out.println(“Key :”+keys.next()+”Value:”+ht.get(keys.next()));
}
}
}
public class HashMapExample {
public static void main(String []args){
HashMap hm = new HashMap();
hm.put(“Dev”, “Viswam”);
hm.put(“QC”,”Viswam”);
hm.put(“QC”,”Sunitha”);
hm.put(“QC”,”Darling”);
hm.put(“Dev”, “Deepak”);
hm.put(“CCM”, “Viswam”);
Iterator it = hm.keySet().iterator();
while(it.hasNext()){
String key = it.next();
System.out.println(“Key ==”+key+”Values==>”+hm.get(key));
}
}
}