Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




KOTLIN - HASH TABLE CODE




Example :



import java.util.Hashtable;

fun main(arr: Array<String>) {

    var hashtable = Hashtable<String, Int>();

    hashtable.put("ABA", 13);
    hashtable.put("CAB", 12);
    hashtable.put("BAC", 15);

    println(hashtable);

    var i = hashtable.get("ABA");

    println("ABAs age is "+i);

    var j = hashtable.get("BAC");

    println("BACs age is "+j);

}


Output :



  {CAB=12, ABA=13, BAC=15}
  ABAs age is 13
  BACs age is 15

Code explanation for Hash Table


Luckily, kotlin already provides Hashtable defined in kotlin.util.Hashtable.


All we have done is imported it and used it.


import java.util.Hashtable;

As we know we have stored the names ABA, CAB and BAC and their corresponding ages 13, 12 and 15 in the Hashtable.


hashtable.put("ABA", 13);
hashtable.put("CAB", 12);
hashtable.put("BAC", 15);

But how they are stored in the HashTable will be decided by kotlin. As we are using the Hashtable provided by kotlin.


So, for ABA, a Hash Code is calculated by kotlin and the age of ABA is stored in some location decided by kotlin.


Similarly, the age of CAB and BAC is stored in the Hashtable after kotlin calculates the Hash Code, and decides where they will be stored.


After all the values are stored, we then check all the values stored in the Hashtable.


println(hashtable);

Then we try to retrieve the age of ABA.


var i = hashtable.get("ABA");

So, we pass the name of ABA and internally kotlin calculates the Hash Code for ABA and gives us the age of ABA from the Hashtable.


And we print the age of ABA on the screen.


println("ABAs age is "+i);

Similarly we retrieve the age of BAC and print it on the screen.


var j = hashtable.get("BAC");

println("BACs age is "+j);