Hashtable

  • Underlying data structure is Hashtable
  • Insertion order is not preserved
  • Based on Hashcode of keys
  • Duplicates keys are not allowed but duplicate values are allowed
  • Heterogenious values are allowed for both keys are values.
  • Null not allowed for keys and value
  • Implements Seralizable, Clonable but not RandomAccess
  • All the methods are synchronized hence Hashtable objects are ThreadSafe
  • Best if frequent operation is search in multithreading environment.

Constructors

  • Hastable h = new Hashtable()
    • Empty hash table with initial capacity 11
    • Load Factor 0.75
  • Hastable h = new Hashtable(int initialCapacity)
    • Load Factor 0.75
    • InitialCapacity set via constructor
  • Hastable h = new Hashtable(int initialCapacity, float fillRatio)
    • LoadFactor and Initital Capacity both is given as input
  • Hastable h = new Hashtable(Map m)
    • Cross collection conversion

Internal Working of a Hashtable

  • Hashtable works on Hashing principles
  • Object class has a hashCode() method which returns a integer value which is the HashCode

Example :

For our example we will store objects of class Temp in the Hastable

Explaination :

Temp Class

  • We have overridden the hashCode() of the Temp class so that an integer that we pass is the HashCode of for that object
  • We have overridden the toString() method so that the integer itself is returned

Main Method Execution

  • We create a Hashtable with name h, since no initial capacity is passed the default value is 11
    • A bucket is created with size 11
  • We add 1st value to it i.e new Temp(5),”A”
    • Now is here the key is object Temp(5) and the value is A
    • We have overridden the Hashcode of the temp class and we know of a fact that its hashcode is 5
    • Now we calculate the location of value “A” in the bucker
    • We calculate that by formula hash%capacity i.e 5%11 = 5
    • So the value 5=A will be stored at location 5 in the bucket
  • Similarly for new Temp(2),”B” location 2
  • Similarly for new Temp(6),”C” location 6
  • Similarly for new Temp(15),”D” location 4
  • Similarly for new Temp(23),”E” location 1
  • For new Temp(16),”F” we have hashcollision
    • For hashcollision we use the same bucket a location right to it
  • Thus all the values are stored in the HashTable
  • Printing of Hashtable
    • Printing of Hashtable happens from top to bottom ie. from index 10 to 0
    • If 2 values are present inside a bucket then from right to left
    • Hence the output 6=C, 16=F, 5=A, 15=D, 2=B, 23=E}

Example 2 : When the hashing logic hashCode() changes complete hashtable structure changes

Example 3: Increasing initial capacity and the Hashtable structure change

Leave a Comment